1Layout::PatternLayout(3U)ser Contributed Perl DocumentatiLoanyout::PatternLayout(3)
2
3
4
6 Log::Log4perl::Layout::PatternLayout - Pattern Layout
7
9 use Log::Log4perl::Layout::PatternLayout;
10
11 my $layout = Log::Log4perl::Layout::PatternLayout->new(
12 "%d (%F:%L)> %m");
13
15 Creates a pattern layout according to
16 http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html
17 and a couple of Log::Log4perl-specific extensions.
18
19 The "new()" method creates a new PatternLayout, specifying its log
20 format. The format string can contain a number of placeholders which
21 will be replaced by the logging engine when it's time to log the
22 message:
23
24 %c Category of the logging event.
25 %C Fully qualified package (or class) name of the caller
26 %d Current date in yyyy/MM/dd hh:mm:ss format
27 %d{...} Current date in customized format (see below)
28 %F File where the logging event occurred
29 %H Hostname (if Sys::Hostname is available)
30 %l Fully qualified name of the calling method followed by the
31 callers source the file name and line number between
32 parentheses.
33 %L Line number within the file where the log statement was issued
34 %m The message to be logged
35 %m{chomp} Log message, stripped off a trailing newline
36 %m{indent} Log message, multi-lines indented so they line up with first
37 %m{indent=n} Log message, multi-lines indented by n spaces
38 %M Method or function where the logging request was issued
39 %n Newline (OS-independent)
40 %p Priority of the logging event (%p{1} shows the first letter)
41 %P pid of the current process
42 %r Number of milliseconds elapsed from program start to logging
43 event
44 %R Number of milliseconds elapsed from last logging event to
45 current logging event
46 %T A stack trace of functions called
47 %x The topmost NDC (see below)
48 %X{key} The entry 'key' of the MDC (see below)
49 %% A literal percent (%) sign
50
51 NDC and MDC are explained in "Nested Diagnostic Context (NDC)" in
52 Log::Log4perl and "Mapped Diagnostic Context (MDC)" in Log::Log4perl.
53
54 The granularity of time values is milliseconds if Time::HiRes is
55 available. If not, only full seconds are used.
56
57 Every once in a while, someone uses the "%m%n" pattern and additionally
58 provides an extra newline in the log message (e.g.
59 "->log("message\n")". To avoid printing an extra newline in this case,
60 the PatternLayout will chomp the message, printing only one newline.
61 This option can be controlled by PatternLayout's
62 "message_chomp_before_newline" option. See "Advanced options" for
63 details.
64
65 Quantify placeholders
66 All placeholders can be extended with formatting instructions, just
67 like in printf:
68
69 %20c Reserve 20 chars for the category, right-justify and fill
70 with blanks if it is shorter
71 %-20c Same as %20c, but left-justify and fill the right side
72 with blanks
73 %09r Zero-pad the number of milliseconds to 9 digits
74 %.8c Specify the maximum field with and have the formatter
75 cut off the rest of the value
76
77 Fine-tuning with curlies
78 Some placeholders have special functions defined if you add curlies
79 with content after them:
80
81 %c{1} Just show the right-most category compontent, useful in large
82 class hierarchies (Foo::Baz::Bar -> Bar)
83 %c{2} Just show the two right most category components
84 (Foo::Baz::Bar -> Baz::Bar)
85
86 %F Display source file including full path
87 %F{1} Just display filename
88 %F{2} Display filename and last path component (dir/test.log)
89 %F{3} Display filename and last two path components (d1/d2/test.log)
90
91 %M Display fully qualified method/function name
92 %M{1} Just display method name (foo)
93 %M{2} Display method name and last path component (main::foo)
94
95 In this way, you're able to shrink the displayed category or limit
96 file/path components to save space in your logs.
97
98 Fine-tune the date
99 If you're not happy with the default %d format for the date which looks
100 like
101
102 yyyy/MM/DD HH:mm:ss
103
104 (which is slightly different from Log4j which uses "yyyy-MM-dd
105 HH:mm:ss,SSS") you're free to fine-tune it in order to display only
106 certain characteristics of a date, according to the SimpleDateFormat in
107 the Java World
108 (http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html):
109
110 %d{HH:mm} "23:45" -- Just display hours and minutes
111 %d{yy, EEEE} "02, Monday" -- Just display two-digit year
112 and spelled-out weekday
113 %d{e} "1473741760" -- Epoch seconds
114 %d{h a} "12 PM" -- Hour and am/pm marker
115 ... and many more
116
117 For an exhaustive list of all supported date features, look at
118 Log::Log4perl::DateFormat.
119
120 Custom cspecs
121 First of all, "cspecs" is short for "conversion specifiers", which is
122 the log4j and the printf(3) term for what Mike is calling
123 "placeholders." I suggested "cspecs" for this part of the api before I
124 saw that Mike was using "placeholders" consistently in the log4perl
125 documentation. Ah, the joys of collaboration ;=) --kg
126
127 If the existing corpus of placeholders/cspecs isn't good enough for
128 you, you can easily roll your own:
129
130 #'U' a global user-defined cspec
131 log4j.PatternLayout.cspec.U = sub { return "UID: $< "}
132
133 #'K' cspec local to appndr1 (pid in hex)
134 log4j.appender.appndr1.layout.cspec.K = sub { return sprintf "%1x", $$}
135
136 #and now you can use them
137 log4j.appender.appndr1.layout.ConversionPattern = %K %U %m%n
138
139 The benefit of this approach is that you can define and use the cspecs
140 right next to each other in the config file.
141
142 If you're an API kind of person, there's also this call:
143
144 Log::Log4perl::Layout::PatternLayout::
145 add_global_cspec('Z', sub {'zzzzzzzz'}); #snooze?
146
147 When the log message is being put together, your anonymous sub will be
148 called with these arguments:
149
150 ($layout, $message, $category, $priority, $caller_level);
151
152 layout: the PatternLayout object that called it
153 message: the logging message (%m)
154 category: e.g. groceries.beverages.adult.beer.schlitz
155 priority: e.g. DEBUG|WARN|INFO|ERROR|FATAL
156 caller_level: how many levels back up the call stack you have
157 to go to find the caller
158
159 Please note that the subroutines you're defining in this way are going
160 to be run in the "main" namespace, so be sure to fully qualify
161 functions and variables if they're located in different packages. Also
162 make sure these subroutines aren't using Log4perl, otherwise Log4perl
163 will enter an infinite recursion.
164
165 With Log4perl 1.20 and better, cspecs can be written with parameters in
166 curly braces. Writing something like
167
168 log4perl.appender.Screen.layout.ConversionPattern = %U{user} %U{id} %m%n
169
170 will cause the cspec function defined for %U to be called twice, once
171 with the parameter 'user' and then again with the parameter 'id', and
172 the placeholders in the cspec string will be replaced with the
173 respective return values.
174
175 The parameter value is available in the 'curlies' entry of the first
176 parameter passed to the subroutine (the layout object reference). So,
177 if you wanted to map %U{xxx} to entries in the POE session hash, you'd
178 write something like:
179
180 log4perl.PatternLayout.cspec.U = sub { \
181 POE::Kernel->get_active_session->get_heap()->{ $_[0]->{curlies} } }
182
183 SECURITY NOTE
184
185 This feature means arbitrary perl code can be embedded in the config
186 file. In the rare case where the people who have access to your config
187 file are different from the people who write your code and shouldn't
188 have execute rights, you might want to set
189
190 $Log::Log4perl::Config->allow_code(0);
191
192 before you call init(). Alternatively you can supply a restricted set
193 of Perl opcodes that can be embedded in the config file as described in
194 "Restricting what Opcodes can be in a Perl Hook" in Log::Log4perl.
195
196 Advanced Options
197 The constructor of the "Log::Log4perl::Layout::PatternLayout" class
198 takes an optional hash reference as a first argument to specify
199 additional options in order to (ab)use it in creative ways:
200
201 my $layout = Log::Log4perl::Layout::PatternLayout->new(
202 { time_function => \&my_time_func,
203 },
204 "%d (%F:%L)> %m");
205
206 Here's a list of parameters:
207
208 time_function
209 Takes a reference to a function returning the time for the
210 time/date fields, either in seconds since the epoch or as an array,
211 carrying seconds and microseconds, just like
212 "Time::HiRes::gettimeofday" does.
213
214 message_chomp_before_newline
215 If a layout contains the pattern "%m%n" and the message ends with a
216 newline, PatternLayout will chomp the message, to prevent printing
217 two newlines. If this is not desired, and you want two newlines in
218 this case, the feature can be turned off by setting the
219 "message_chomp_before_newline" option to a false value:
220
221 my $layout = Log::Log4perl::Layout::PatternLayout->new(
222 { message_chomp_before_newline => 0
223 },
224 "%d (%F:%L)> %m%n");
225
226 In a Log4perl configuration file, the feature can be turned off
227 like this:
228
229 log4perl.appender.App.layout = PatternLayout
230 log4perl.appender.App.layout.ConversionPattern = %d %m%n
231 # Yes, I want two newlines
232 log4perl.appender.App.layout.message_chomp_before_newline = 0
233
234 Getting rid of newlines
235 If your code contains logging statements like
236
237 # WRONG, don't do that!
238 $logger->debug("Some message\n");
239
240 then it's usually best to strip the newlines from these calls. As
241 explained in "Logging newlines" in Log::Log4perl, logging statements
242 should never contain newlines, but rely on appender layouts to add
243 necessary newlines instead.
244
245 If changing the code is not an option, use the special PatternLayout
246 placeholder %m{chomp} to refer to the message excluding a trailing
247 newline:
248
249 log4perl.appender.App.layout.ConversionPattern = %d %m{chomp}%n
250
251 This will add a single newline to every message, regardless if it
252 complies with the Log4perl newline guidelines or not (thanks to Tim
253 Bunce for this idea).
254
255 Multi Lines
256 If a log message consists of several lines, like
257
258 $logger->debug("line1\nline2\nline3");
259
260 then by default, they get logged like this (assuming the the layout is
261 set to "%d>%m%n"):
262
263 # layout %d>%m%n
264 2014/07/27 12:46:16>line1
265 line2
266 line3
267
268 If you'd rather have the messages aligned like
269
270 # layout %d>%m{indent}%n
271 2014/07/27 12:46:16>line1
272 line2
273 line3
274
275 then use the %m{indent} option for the %m specifier. This option can
276 also take a fixed value, as in %m{indent=2}, which indents subsequent
277 lines by two spaces:
278
279 # layout %d>%m{indent=2}%n
280 2014/07/27 12:46:16>line1
281 line2
282 line3
283
284 Note that you can still add the "chomp" option for the %m specifier in
285 this case (see above what it does), simply add it after a separating
286 comma, like in %m{indent=2,chomp}.
287
289 Copyright 2002-2013 by Mike Schilli <m@perlmeister.com> and Kevin Goess
290 <cpan@goess.org>.
291
292 This library is free software; you can redistribute it and/or modify it
293 under the same terms as Perl itself.
294
296 Please contribute patches to the project on Github:
297
298 http://github.com/mschilli/log4perl
299
300 Send bug reports or requests for enhancements to the authors via our
301
302 MAILING LIST (questions, bug reports, suggestions/patches):
303 log4perl-devel@lists.sourceforge.net
304
305 Authors (please contact them via the list above, not directly): Mike
306 Schilli <m@perlmeister.com>, Kevin Goess <cpan@goess.org>
307
308 Contributors (in alphabetical order): Ateeq Altaf, Cory Bennett, Jens
309 Berthold, Jeremy Bopp, Hutton Davidson, Chris R. Donnelly, Matisse
310 Enzer, Hugh Esco, Anthony Foiani, James FitzGibbon, Carl Franks, Dennis
311 Gregorovic, Andy Grundman, Paul Harrington, Alexander Hartmaier David
312 Hull, Robert Jacobson, Jason Kohles, Jeff Macdonald, Markus Peter,
313 Brett Rann, Peter Rabbitson, Erik Selberg, Aaron Straup Cope, Lars
314 Thegler, David Viner, Mac Yang.
315
316
317
318perl v5.30.1 2020-01-30 Layout::PatternLayout(3)