Not a blog

Mojolicious and Sprintf Loggin

Don’t want to write things like

app->log->debug("foo $config->{foo} versus ".stat->mtime." seconds");

but rather

app->log->debug("foo %s versus %d seconds", $config->{foo}, stat->mtime);

but Mojo::Log does not support that directly. You could use this:

app->log->debug(sprintf("foo %s  versus %d seconds", $config->{foo}, stat->mtime));

with the downside that sprintf() is called even if the message would not be logged due to your app’s log level being higher than that of the call.

Alternatively you could base your own logger class on Mojo::Log:


package My::Log;
use base Mojo::Log;

sub format {
        my ($self, $level, $format, @parameters) = @_;

        return $self->SUPER::format($level, sprintf($format, @parameters));

package main;

use Mojolicious::Lite;

app->log->error("this string %s printf %s", 'uses', 'stuff');
app->log->warn('decimal: %d hex: %x', 16, 16);
app->log->info('pi: %.2f', 3.14159265359);

And it’s output:

[Wed Feb 27 17:24:34 2013] [error] this string uses printf stuff
[Wed Feb 27 17:24:34 2013] [warn] decimal: 16 hex: 10
[Wed Feb 27 17:24:34 2013] [info] pi: 3.14