Search code examples
perlloggingtimezonelog4perl

How can I log the timezone with Log::Log4perl?


We use Log::Log4perl to log the current date like this:

log4perl.appender.perllog.layout.ConversionPattern=%d{yyyyMMdd.hhmmss:}-%P-%H-%p{2}-%m

Is there a way to log the timezone as well?


Solution

  • The date formats in Log::Log4perl::Layout::PatternLayout are implemented by Log::Log4perl::DateFormat , which supports the Z specifier for timezone offset:

    use strict;
    use warnings 'all';
    
    use Log::Log4perl;
    
    my $conf = <<'CONF';
        log4perl.logger.Foo = INFO, perllog
    
        log4perl.appender.perllog          = Log::Log4perl::Appender::File
        log4perl.appender.perllog.filename = foo.log
        log4perl.appender.perllog.layout   = Log::Log4perl::Layout::PatternLayout
        log4perl.appender.perllog.layout.ConversionPattern = \
            %d{yyyyMMdd.hhmmssZ:}-%P-%H-%p{2}-%m
    CONF
    
    Log::Log4perl::init(\$conf);
    
    my $logger = Log::Log4perl->get_logger('Foo');
    $logger->warn('Hello, timezone!');
    

    Output:

    20160831.094036-0600:-28223-www.example.com-WA-Hello, timezone!
    

    This is not documented in Log::Log4perl::Layout::PatternLayout; generally it's a bad idea to use undocumented features, but in this case it looks like the author just forgot to update the docs in one module when features were added to another. I've submitted a ticket to get the docs updated.