Layout:...rnLayout(3)

πŸ’… Layout:...rnLayout(3) πŸ’…

okay so this is the user contributed Perl documentation page for Log::Log4perl::Layout::PatternLayout, and bestie, it's giving pattern layout realness. ✨

πŸ’– 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 plus a couple of Log::Log4perl-specific extensions. iykyk πŸ’…

The new() method creates a new PatternLayout and specifies its log format. The format string can contain a bunch of placeholders that the logging engine swaps in 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.
  • %d{...} β€” Current date in customized format (see below).
  • %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 caller's source 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{chomp} β€” Log message, stripped off a trailing newline.
  • %m{indent} β€” Log message, multi-lines indented so they line up with the first.
  • %m{indent=n} β€” Log message, multi-lines indented by n spaces.
  • %M β€” Method or function where the logging request was issued.
  • %n β€” Newline (OS-independent).
  • %p β€” Priority/level of the logging event (%p{1} shows the first letter).
  • %P β€” pid of the current process.
  • %r β€” Number of milliseconds elapsed from program start to logging event.
  • %R β€” Number of milliseconds elapsed from last logging event to current 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 Log::Log4perl and "Mapped Diagnostic Context (MDC)" in Log::Log4perl. 🫢

The granularity of time values is milliseconds if Time::HiRes is available. If not, only full seconds are used. no cap, that's the tea ⏱️

Every once in a while, someone uses the "%m%n" pattern and additionally provides an extra newline in the log message (e.g. ->log("message\n")). To avoid printing an extra newline in this case, the PatternLayout will chomp the message, printing only one newline. This option can be controlled by PatternLayout's "message_chomp_before_newline" option. See "Advanced options" for details. 😭


✨ 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 width 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 component, 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).
  • %M β€” Display fully qualified method/function name.
  • %M{1} β€” Just display method name (foo).
  • %M{2} β€” Display method name and last path component (main::foo).

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


πŸ’œ 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://docs.oracle.com/javase/8/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
%d{e}         "1473741760" -- Epoch seconds
%d{h a}       "12 PM"      -- Hour and am/pm marker
... and many more

For an exhaustive list of all supported date features, look at Log::Log4perl::DateFormat. obsessed πŸŽ€


🧚 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 lol 😭

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. periodt πŸ’…

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 message 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

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. Also make sure these subroutines aren't using Log4perl, otherwise Log4perl will enter an infinite recursion. fr fr, do not do that 🚨

With Log4perl 1.20 and better, cspecs can be written with parameters in curly braces. Writing something like

log4perl.appender.Screen.layout.ConversionPattern = %U{user} %U{id} %m%n

will cause the cspec function defined for %U to be called twice, once with the parameter 'user' and then again with the parameter 'id', and the placeholders in the cspec string will be replaced with the respective return values. iconic ✨

The parameter value is available in the 'curlies' entry of the first parameter passed to the subroutine (the layout object reference). So, if you wanted to map %U{xxx} to entries in the POE session hash, you'd write something like:

log4perl.PatternLayout.cspec.U = sub { \
  POE::Kernel->get_active_session->get_heap()->{ $_[0]->{curlies} } }

🚨 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 Log::Log4perl. bestie, please be careful with this one 🫢


🌈 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 an array, carrying seconds and microseconds, just like Time::HiRes::gettimeofday does.

πŸŒ™ message_chomp_before_newline

If a layout contains the pattern "%m%n" and the message ends with a newline, PatternLayout will chomp the message, to prevent printing two newlines. If this is not desired, and you want two newlines in this case, the feature can be turned off by setting the "message_chomp_before_newline" option to a false value:

my $layout = Log::Log4perl::Layout::PatternLayout->new(
    { message_chomp_before_newline => 0
    },
    "%d (%F:%L)> %m%n");

In a Log4perl configuration file, the feature can be turned off like this:

log4perl.appender.App.layout   = PatternLayout
log4perl.appender.App.layout.ConversionPattern = %d %m%n
  # Yes, I want two newlines
log4perl.appender.App.layout.message_chomp_before_newline = 0

πŸ“ Getting rid of newlines πŸ“

If your code contains logging statements like

      # WRONG, don't do that!
    $logger->debug("Some message\n");

then it's usually best to strip the newlines from these calls. As explained in "Logging newlines" in Log::Log4perl, logging statements should never contain newlines, but rely on appender layouts to add necessary newlines instead. say it louder for the people in the back πŸ“’

If changing the code is not an option, use the special PatternLayout placeholder %m{chomp} to refer to the message excluding a trailing newline:

log4perl.appender.App.layout.ConversionPattern = %d %m{chomp}%n

This will add a single newline to every message, regardless if it complies with the Log4perl newline guidelines or not (thanks to Tim Bunce for this idea). king behavior πŸ‘‘


🌟 Multi Lines 🌟

If a log message consists of several lines, like

$logger->debug("line1\nline2\nline3");

then by default, they get logged like this (assuming the layout is set to "%d>%m%n"):

      # layout %d>%m%n
    2014/07/27 12:46:16>line1
    line2
    line3

If you'd rather have the messages aligned like

      # layout %d>%m{indent}%n
    2014/07/27 12:46:16>line1
                        line2
                        line3

...then you reach for the %m{indent} option on the %m specifier, and suddenly everything lines up. πŸ’… This option can also take a fixed value, like %m{indent=2}, which indents the lines that come after it by two spaces:

    # layout %d>%m{indent=2}%n
  2014/07/27 12:46:16>line1
    line2
    line3

And bestie, you can still add the "chomp" option for the %m specifier in this case (scroll up if you forgot what it does 😌) β€” just pop it in after a separating comma, like %m{indent=2,chomp}. Two options, one curly brace, zero drama. ✨


πŸŽ€ LICENSE πŸŽ€

Copyright 2002-2013 by Mike Schilli <m@perlmeister.com> and Kevin Goess <cpan@goess.org>.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

So yeah β€” go wild, remix it, ship it, it's giving open source royalty. πŸ‘‘


πŸ’– AUTHOR πŸ’–

Please contribute patches to the project on Github:

http://github.com/mschilli/log4perl

Send bug reports or requests for enhancements to the authors via our

MAILING LIST (questions, bug reports, suggestions/patches): log4perl-devel@lists.sourceforge.net

Authors (please contact them via the list above, not directly): Mike Schilli <m@perlmeister.com>, Kevin Goess <cpan@goess.org>

Contributors (in alphabetical order): Ateeq Altaf, Cory Bennett, Jens Berthold, Jeremy Bopp, Hutton Davidson, Chris R. Donnelly, Matisse Enzer, Hugh Esco, Anthony Foiani, James FitzGibbon, Carl Franks, Dennis Gregorovic, Andy Grundman, Paul Harrington, Alexander Hartmaier David Hull, Robert Jacobson, Jason Kohles, Jeff Macdonald, Markus Peter, Brett Rann, Peter Rabbitson, Erik Selberg, Aaron Straup Cope, Lars Thegler, David Viner, Mac Yang.

ngl the whole contributor list is a full-on squad and they're all iconic for showing up 🫢 (also yes, that double space between Alexander Hartmaier and David Hull is exactly how it's printed β€” not me messing up, iykyk 😭)

okay that's the whole page, you made it to the end, I'm so proud of you fr fr πŸ¦‹ go indent something and make it gorgeous β€” this one's from perl v5.42.0, dated 2022-10-22, and it's the Layout:...rnLayout(3) page, signing off with main character energy πŸ’œπŸŽ€βœ¨

πŸ“¦ where this page comes from