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 %F File where the logging event occurred
28 %H Hostname (if Sys::Hostname is available)
29 %l Fully qualified name of the calling method followed by the
30 callers source the file name and line number between
31 parentheses.
32 %L Line number within the file where the log statement was issued
33 %m The message to be logged
34 %m{chomp} The message to be logged, stripped off a trailing newline
35 %M Method or function where the logging request was issued
36 %n Newline (OS-independent)
37 %p Priority of the logging event (%p{1} shows the first letter)
38 %P pid of the current process
39 %r Number of milliseconds elapsed from program start to logging
40 event
41 %R Number of milliseconds elapsed from last logging event to
42 current logging event
43 %T A stack trace of functions called
44 %x The topmost NDC (see below)
45 %X{key} The entry 'key' of the MDC (see below)
46 %% A literal percent (%) sign
47
48 NDC and MDC are explained in "Nested Diagnostic Context (NDC)" in
49 Log::Log4perl and "Mapped Diagnostic Context (MDC)" in Log::Log4perl.
50
51 The granularity of time values is milliseconds if Time::HiRes is
52 available. If not, only full seconds are used.
53
54 Every once in a while, someone uses the "%m%n" pattern and additionally
55 provides an extra newline in the log message (e.g.
56 "->log("message\n")". To avoid printing an extra newline in this case,
57 the PatternLayout will chomp the message, printing only one newline.
58 This option can be controlled by PatternLayout's
59 "message_chomp_before_newline" option. See "Advanced options" for
60 details.
61
62 Quantify placeholders
63 All placeholders can be extended with formatting instructions, just
64 like in printf:
65
66 %20c Reserve 20 chars for the category, right-justify and fill
67 with blanks if it is shorter
68 %-20c Same as %20c, but left-justify and fill the right side
69 with blanks
70 %09r Zero-pad the number of milliseconds to 9 digits
71 %.8c Specify the maximum field with and have the formatter
72 cut off the rest of the value
73
74 Fine-tuning with curlies
75 Some placeholders have special functions defined if you add curlies
76 with content after them:
77
78 %c{1} Just show the right-most category compontent, useful in large
79 class hierarchies (Foo::Baz::Bar -> Bar)
80 %c{2} Just show the two right most category components
81 (Foo::Baz::Bar -> Baz::Bar)
82
83 %F Display source file including full path
84 %F{1} Just display filename
85 %F{2} Display filename and last path component (dir/test.log)
86 %F{3} Display filename and last two path components (d1/d2/test.log)
87
88 %M Display fully qualified method/function name
89 %M{1} Just display method name (foo)
90 %M{2} Display method name and last path component (main::foo)
91
92 In this way, you're able to shrink the displayed category or limit
93 file/path components to save space in your logs.
94
95 Fine-tune the date
96 If you're not happy with the default %d format for the date which looks
97 like
98
99 yyyy/MM/DD HH:mm:ss
100
101 (which is slightly different from Log4j which uses "yyyy-MM-dd
102 HH:mm:ss,SSS") you're free to fine-tune it in order to display only
103 certain characteristics of a date, according to the SimpleDateFormat in
104 the Java World
105 (http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html):
106
107 %d{HH:mm} "23:45" -- Just display hours and minutes
108 %d{yy, EEEE} "02, Monday" -- Just display two-digit year
109 and spelled-out weekday
110 Here's the symbols and their meaning, according to the SimpleDateFormat
111 specification:
112
113 Symbol Meaning Presentation Example
114 ------ ------- ------------ -------
115 G era designator (Text) AD
116 y year (Number) 1996
117 M month in year (Text & Number) July & 07
118 d day in month (Number) 10
119 h hour in am/pm (1-12) (Number) 12
120 H hour in day (0-23) (Number) 0
121 m minute in hour (Number) 30
122 s second in minute (Number) 55
123 E day in week (Text) Tuesday
124 D day in year (Number) 189
125 a am/pm marker (Text) PM
126
127 (Text): 4 or more pattern letters--use full form, < 4--use short or
128 abbreviated form if one exists.
129
130 (Number): the minimum number of digits. Shorter numbers are
131 zero-padded to this amount. Year is handled
132 specially; that is, if the count of 'y' is 2, the
133 Year will be truncated to 2 digits.
134
135 (Text & Number): 3 or over, use text, otherwise use number.
136
137 There's also a bunch of pre-defined formats:
138
139 %d{ABSOLUTE} "HH:mm:ss,SSS"
140 %d{DATE} "dd MMM yyyy HH:mm:ss,SSS"
141 %d{ISO8601} "yyyy-MM-dd HH:mm:ss,SSS"
142
143 Custom cspecs
144 First of all, "cspecs" is short for "conversion specifiers", which is
145 the log4j and the printf(3) term for what Mike is calling
146 "placeholders." I suggested "cspecs" for this part of the api before I
147 saw that Mike was using "placeholders" consistently in the log4perl
148 documentation. Ah, the joys of collaboration ;=) --kg
149
150 If the existing corpus of placeholders/cspecs isn't good enough for
151 you, you can easily roll your own:
152
153 #'U' a global user-defined cspec
154 log4j.PatternLayout.cspec.U = sub { return "UID: $< "}
155
156 #'K' cspec local to appndr1 (pid in hex)
157 log4j.appender.appndr1.layout.cspec.K = sub { return sprintf "%1x", $$}
158
159 #and now you can use them
160 log4j.appender.appndr1.layout.ConversionPattern = %K %U %m%n
161
162 The benefit of this approach is that you can define and use the cspecs
163 right next to each other in the config file.
164
165 If you're an API kind of person, there's also this call:
166
167 Log::Log4perl::Layout::PatternLayout::
168 add_global_cspec('Z', sub {'zzzzzzzz'}); #snooze?
169
170 When the log message is being put together, your anonymous sub will be
171 called with these arguments:
172
173 ($layout, $message, $category, $priority, $caller_level);
174
175 layout: the PatternLayout object that called it
176 message: the logging message (%m)
177 category: e.g. groceries.beverages.adult.beer.schlitz
178 priority: e.g. DEBUG|WARN|INFO|ERROR|FATAL
179 caller_level: how many levels back up the call stack you have
180 to go to find the caller
181
182 Please note that the subroutines you're defining in this way are going
183 to be run in the "main" namespace, so be sure to fully qualify
184 functions and variables if they're located in different packages. Also
185 make sure these subroutines aren't using Log4perl, otherwise Log4perl
186 will enter an infinite recursion.
187
188 With Log4perl 1.20 and better, cspecs can be written with parameters in
189 curly braces. Writing something like
190
191 log4perl.appender.Screen.layout.ConversionPattern = %U{user} %U{id} %m%n
192
193 will cause the cspec function defined for %U to be called twice, once
194 with the parameter 'user' and then again with the parameter 'id', and
195 the placeholders in the cspec string will be replaced with the
196 respective return values.
197
198 The parameter value is available in the 'curlies' entry of the first
199 parameter passed to the subroutine (the layout object reference). So,
200 if you wanted to map %U{xxx} to entries in the POE session hash, you'd
201 write something like:
202
203 log4perl.PatternLayout.cspec.U = sub { \
204 POE::Kernel->get_active_session->get_heap()->{ $_[0]->{curlies} } }
205
206 SECURITY NOTE
207
208 This feature means arbitrary perl code can be embedded in the config
209 file. In the rare case where the people who have access to your config
210 file are different from the people who write your code and shouldn't
211 have execute rights, you might want to set
212
213 $Log::Log4perl::Config->allow_code(0);
214
215 before you call init(). Alternatively you can supply a restricted set
216 of Perl opcodes that can be embedded in the config file as described in
217 "Restricting what Opcodes can be in a Perl Hook" in Log::Log4perl.
218
219 Advanced Options
220 The constructor of the "Log::Log4perl::Layout::PatternLayout" class
221 takes an optional hash reference as a first argument to specify
222 additional options in order to (ab)use it in creative ways:
223
224 my $layout = Log::Log4perl::Layout::PatternLayout->new(
225 { time_function => \&my_time_func,
226 },
227 "%d (%F:%L)> %m");
228
229 Here's a list of parameters:
230
231 time_function
232 Takes a reference to a function returning the time for the
233 time/date fields, either in seconds since the epoch or as an array,
234 carrying seconds and microseconds, just like
235 "Time::HiRes::gettimeofday" does.
236
237 message_chomp_before_newline
238 If a layout contains the pattern "%m%n" and the message ends with a
239 newline, PatternLayout will chomp the message, to prevent printing
240 two newlines. If this is not desired, and you want two newlines in
241 this case, the feature can be turned off by setting the
242 "message_chomp_before_newline" option to a false value:
243
244 my $layout = Log::Log4perl::Layout::PatternLayout->new(
245 { message_chomp_before_newline => 0
246 },
247 "%d (%F:%L)> %m%n");
248
249 In a Log4perl configuration file, the feature can be turned off
250 like this:
251
252 log4perl.appender.App.layout = PatternLayout
253 log4perl.appender.App.layout.ConversionPattern = %d %m%n
254 # Yes, I want two newlines
255 log4perl.appender.App.layout.message_chomp_before_newline = 0
256
257 Getting rid of newlines
258 If your code contains logging statements like
259
260 # WRONG, don't do that!
261 $logger->debug("Some message\n");
262
263 then it's usually best to strip the newlines from these calls. As
264 explained in "Logging newlines" in Log::Log4perl, logging statements
265 should never contain newlines, but rely on appender layouts to add
266 necessary newlines instead.
267
268 If changing the code is not an option, use the special PatternLayout
269 placeholder %m{chomp} to refer to the message excluding a trailing
270 newline:
271
272 log4perl.appender.App.layout.ConversionPattern = %d %m{chomp}%n
273
274 This will add a single newline to every message, regardless if it
275 complies with the Log4perl newline guidelines or not (thanks to Tim
276 Bunce for this idea).
277
279 Copyright 2002-2009 by Mike Schilli <m@perlmeister.com> and Kevin Goess
280 <cpan@goess.org>.
281
282 This library is free software; you can redistribute it and/or modify it
283 under the same terms as Perl itself.
284
285
286
287perl v5.12.2 2010-08-31 Layout::PatternLayout(3)