bob_saginowski
bob_saginowski

Reputation: 1429

Redirect and Restore STDERR in Dancer

When starting my http server I don't want to see >> Dancer2 v0.201000 server <pid> listening on http://0.0.0.0:<port> printed on the stderr. Thats why I added the following line before calling start()

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";

    start();
}

startServer();

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

Upvotes: 4

Views: 421

Answers (2)

simbabque
simbabque

Reputation: 54381

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.

Upvotes: 2

Chankey Pathak
Chankey Pathak

Reputation: 21676

You could use select before redirecting to save it in a variable

my $oldfh = select(STDERR);

and then use it later

select($oldfh);

Also check out:

Upvotes: 0

Related Questions