Log::Log4perl::Layout::PatternLayout - Pattern Layout


NAME

Log::Log4perl::Layout::PatternLayout - Pattern Layout


SYNOPSIS

  use Log::Log4perl::Layout::PatternLayout;
  my $layout = Log::Log4perl::Layout::PatternLayout->new(
                                                   "%d (%F:%L)> %m");


DESCRIPTION

Creates a pattern layout according to http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html and a couple of Log::Log4perl-specific extensions.

The new() method creates a new PatternLayout, specifying its log format. The format string can contain a number of placeholders which will be replaced by the logging engine when it's time to log the message:

    %c Category of the logging event.
    %C Fully qualified package (or class) name of the caller
    %d Current date in yyyy/MM/dd hh:mm:ss format
    %F File where the logging event occurred
    %H Hostname (if Sys::Hostname is available)
    %l Fully qualified name of the calling method followed by the
       callers source the file name and line number between 
       parentheses.
    %L Line number within the file where the log statement was issued
    %m The message to be logged
    %M Method or function where the logging request was issued
    %n Newline (OS-independent)
    %p Priority of the logging event
    %P pid of the current process
    %r Number of milliseconds elapsed from program start to logging 
       event
    %T A stack trace of functions called
    %x The topmost NDC (see below)
    %X{key} The entry 'key' of the MDC (see below)
    %% A literal percent (%) sign

NDC and MDC are explained in Nested Diagnostic Context (NDC) in the Log::Log4perl manpage and Mapped Diagnostic Context (MDC) in the Log::Log4perl manpage.

The granularity of time values is milliseconds if Time::HiRes is available. If not, only full seconds are used.

Quantify placeholders

All placeholders can be extended with formatting instructions, just like in printf:

    %20c   Reserve 20 chars for the category, right-justify and fill
           with blanks if it is shorter
    %-20c  Same as %20c, but left-justify and fill the right side 
           with blanks
    %09r   Zero-pad the number of milliseconds to 9 digits
    %.8c   Specify the maximum field with and have the formatter
           cut off the rest of the value

Fine-tuning with curlies

Some placeholders have special functions defined if you add curlies with content after them:

    %c{1}  Just show the right-most category compontent, useful in large
           class hierarchies (Foo::Baz::Bar -> Bar)
    %c{2}  Just show the two right most category components
           (Foo::Baz::Bar -> Baz::Bar)
    %F     Display source file including full path
    %F{1}  Just display filename
    %F{2}  Display filename and last path component (dir/test.log)
    %F{3}  Display filename and last two path components (d1/d2/test.log)

In this way, you're able to shrink the displayed category or limit file/path components to save space in your logs.

Fine-tune the date

If you're not happy with the default %d format for the date which looks like

    yyyy/MM/DD HH:mm:ss

(which is slightly different from Log4j which uses yyyy-MM-dd HH:mm:ss,SSS) you're free to fine-tune it in order to display only certain characteristics of a date, according to the SimpleDateFormat in the Java World (http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html):

    %d{HH:mm}     "23:45" -- Just display hours and minutes
    %d{yy, EEEE}  "02, Monday" -- Just display two-digit year 
                                  and spelled-out weekday
Here's the symbols and their meaning, according to the SimpleDateFormat
specification:
    Symbol   Meaning                 Presentation     Example
    ------   -------                 ------------     -------
    G        era designator          (Text)           AD
    y        year                    (Number)         1996 
    M        month in year           (Text & Number)  July & 07
    d        day in month            (Number)         10
    h        hour in am/pm (1-12)    (Number)         12
    H        hour in day (0-23)      (Number)         0
    m        minute in hour          (Number)         30
    s        second in minute        (Number)         55
    E        day in week             (Text)           Tuesday
    D        day in year             (Number)         189
    a        am/pm marker            (Text)           PM
    (Text): 4 or more pattern letters--use full form, < 4--use short or 
            abbreviated form if one exists.
    (Number): the minimum number of digits. Shorter numbers are 
              zero-padded to this amount. Year is handled 
              specially; that is, if the count of 'y' is 2, the 
              Year will be truncated to 2 digits.
    (Text & Number): 3 or over, use text, otherwise use number.

There's also a bunch of pre-defined formats:

    %d{ABSOLUTE}   "HH:mm:ss,SSS"
    %d{DATE}       "dd MMM yyyy HH:mm:ss,SSS"
    %d{ISO8601}    "yyyy-MM-dd HH:mm:ss,SSS"

Custom cspecs

First of all, ``cspecs'' is short for ``conversion specifiers'', which is the log4j and the printf(3) term for what Mike is calling ``placeholders.'' I suggested ``cspecs'' for this part of the api before I saw that Mike was using ``placeholders'' consistently in the log4perl documentation. Ah, the joys of collaboration ;=) --kg

If the existing corpus of placeholders/cspecs isn't good enough for you, you can easily roll your own:

    #'U' a global user-defined cspec     
    log4j.PatternLayout.cspec.U = sub { return "UID: $< "}

    #'K' cspec local to appndr1                 (pid in hex)
    log4j.appender.appndr1.layout.cspec.K = sub { return sprintf "%1x", $$}

    #and now you can use them
    log4j.appender.appndr1.layout.ConversionPattern = %K %U %m%n

The benefit of this approach is that you can define and use the cspecs right next to each other in the config file.

If you're an API kind of person, there's also this call:

    Log::Log4perl::Layout::PatternLayout::
                    add_global_cspec('Z', sub {'zzzzzzzz'}); #snooze?

When the log messages is being put together, your anonymous sub will be called with these arguments:

    ($layout, $message, $category, $priority, $caller_level);

    layout: the PatternLayout object that called it
    message: the logging message (%m)
    category: e.g. groceries.beverages.adult.beer.schlitz
    priority: e.g. DEBUG|WARN|INFO|ERROR|FATAL
    caller_level: how many levels back up the call stack you have 
        to go to find the caller

There are currently some issues around providing API access to an appender-specific cspec, but let us know if this is something you want.

Please note that the subroutines you're defining in this way are going to be run in the main namespace, so be sure to fully qualify functions and variables if they're located in different packages.

SECURITY NOTE


This feature means arbitrary perl code can be embedded in the config file. 
In the rare case where the people who have access to your config file are
different from the people who write your code and shouldn't have execute
rights, you might want to set
    $Log::Log4perl::Config->allow_code(0);

before you call init(). Alternatively you can supply a restricted set of Perl opcodes that can be embedded in the config file as described in Restricting what Opcodes can be in a Perl Hook in the Log::Log4perl manpage.


=head2 Advanced Options

The constructor of the Log::Log4perl::Layout::PatternLayout class takes an optional hash reference as a first argument to specify additional options in order to (ab)use it in creative ways:

  my $layout = Log::Log4perl::Layout::PatternLayout->new(
    { time_function       => \&my_time_func,
    }, 
    "%d (%F:%L)> %m");

Here's a list of parameters:

time_function
Takes a reference to a function returning the time for the time/date fields, either in seconds since the epoch or as a reference to an array, carrying seconds and microseconds, just like Time::HiRes::gettimeofday does.


SEE ALSO


AUTHOR

Mike Schilli, <m@perlmeister.com>

 Log::Log4perl::Layout::PatternLayout - Pattern Layout