bob_saginowski bob_saginowski - 1 month ago 4
Perl Question

Redirect and Restore STDERR in Dancer

When starting my

http server
I don't want to see
>> Dancer2 v0.201000 server <pid> listening on<port>
printed on the
. Thats why I added the following line before calling

get "/pwd" => sub {
my $pwd = cwd;
print STDERR "\n\n[PWD] : $pwd\n"; # this line is not being printed
print "\n\n[STDOUT::PWD] : $pwd\n";
my %responseHash = ( pwd => $pwd );
my $response = encode_json \%responseHash;
return $response;

my $dancerStartErr;

sub startServer {
open (local *STDERR, ">", \$dancerStartErr)
or die "Dup err to variable error: $!\n";



The problem is that later I can't print something on the
. How can I reopen
open(STDERR, ">", \*STDERR);
doesn't help)?


If you don't want your application to log anything, you can change the logging engine to use Dancer2::Logger::Null. You do that by editing your config.yml, or in one of your environments. For example, to turn it off in producion, change # appdir/environments/production.yml.

logger: 'null'

The default is the logging engine 'console', which prints stuff to your terminal.

There are other Dancer2::Logger:: classes available bundled with Dancer2 and on CPAN in their own distributions. A better solution to just dumping everything into a black hole might be to log to a file instead. Documentation of how to configure it further can be found in Dancer2::Core::Role::Logger.

Also note that instead of printing to STDERR in your code, you should use the logging keywords with the appropriate log level.

print STDERR "\n\n[PWD] : $pwd\n"; # this line is not being printed

This is not a good idea, because you cannot distinguish if this is an error, or a warning, or just debugging output. That's why there are different log levels built into Dancer2.

  • core
  • debug
  • info
  • warning
  • error

All of them are available as keywords. There is documentation on it in Dancer2::Manual.

Since the working directory is probably not relevant in production, but only during development, you'd go with debug.

debug "[PWD] : $pwd";

That's it. It takes care of newlines and such for you automatically.