| 1 |
###################################################################### |
| 2 |
Log::Log4perl 1.49 |
| 3 |
###################################################################### |
| 4 |
|
| 5 |
NAME |
| 6 |
Log::Log4perl - Log4j implementation for Perl |
| 7 |
|
| 8 |
SYNOPSIS |
| 9 |
# Easy mode if you like it simple ... |
| 10 |
|
| 11 |
use Log::Log4perl qw(:easy); |
| 12 |
Log::Log4perl->easy_init($ERROR); |
| 13 |
|
| 14 |
DEBUG "This doesn't go anywhere"; |
| 15 |
ERROR "This gets logged"; |
| 16 |
|
| 17 |
# ... or standard mode for more features: |
| 18 |
|
| 19 |
Log::Log4perl::init('/etc/log4perl.conf'); |
| 20 |
|
| 21 |
--or-- |
| 22 |
|
| 23 |
# Check config every 10 secs |
| 24 |
Log::Log4perl::init_and_watch('/etc/log4perl.conf',10); |
| 25 |
|
| 26 |
--then-- |
| 27 |
|
| 28 |
$logger = Log::Log4perl->get_logger('house.bedrm.desk.topdrwr'); |
| 29 |
|
| 30 |
$logger->debug('this is a debug message'); |
| 31 |
$logger->info('this is an info message'); |
| 32 |
$logger->warn('etc'); |
| 33 |
$logger->error('..'); |
| 34 |
$logger->fatal('..'); |
| 35 |
|
| 36 |
#####/etc/log4perl.conf############################### |
| 37 |
log4perl.logger.house = WARN, FileAppndr1 |
| 38 |
log4perl.logger.house.bedroom.desk = DEBUG, FileAppndr1 |
| 39 |
|
| 40 |
log4perl.appender.FileAppndr1 = Log::Log4perl::Appender::File |
| 41 |
log4perl.appender.FileAppndr1.filename = desk.log |
| 42 |
log4perl.appender.FileAppndr1.layout = \ |
| 43 |
Log::Log4perl::Layout::SimpleLayout |
| 44 |
###################################################### |
| 45 |
|
| 46 |
ABSTRACT |
| 47 |
Log::Log4perl provides a powerful logging API for your application |
| 48 |
|
| 49 |
DESCRIPTION |
| 50 |
Log::Log4perl lets you remote-control and fine-tune the logging |
| 51 |
behaviour of your system from the outside. It implements the widely |
| 52 |
popular (Java-based) Log4j logging package in pure Perl. |
| 53 |
|
| 54 |
For a detailed tutorial on Log::Log4perl usage, please read |
| 55 |
|
| 56 |
<http://www.perl.com/pub/a/2002/09/11/log4perl.html> |
| 57 |
|
| 58 |
Logging beats a debugger if you want to know what's going on in your |
| 59 |
code during runtime. However, traditional logging packages are too |
| 60 |
static and generate a flood of log messages in your log files that won't |
| 61 |
help you. |
| 62 |
|
| 63 |
"Log::Log4perl" is different. It allows you to control the number of |
| 64 |
logging messages generated at three different levels: |
| 65 |
|
| 66 |
* At a central location in your system (either in a configuration file |
| 67 |
or in the startup code) you specify *which components* (classes, |
| 68 |
functions) of your system should generate logs. |
| 69 |
|
| 70 |
* You specify how detailed the logging of these components should be |
| 71 |
by specifying logging *levels*. |
| 72 |
|
| 73 |
* You also specify which so-called *appenders* you want to feed your |
| 74 |
log messages to ("Print it to the screen and also append it to |
| 75 |
/tmp/my.log") and which format ("Write the date first, then the file |
| 76 |
name and line number, and then the log message") they should be in. |
| 77 |
|
| 78 |
This is a very powerful and flexible mechanism. You can turn on and off |
| 79 |
your logs at any time, specify the level of detail and make that |
| 80 |
dependent on the subsystem that's currently executed. |
| 81 |
|
| 82 |
Let me give you an example: You might find out that your system has a |
| 83 |
problem in the "MySystem::Helpers::ScanDir" component. Turning on |
| 84 |
detailed debugging logs all over the system would generate a flood of |
| 85 |
useless log messages and bog your system down beyond recognition. With |
| 86 |
"Log::Log4perl", however, you can tell the system: "Continue to log only |
| 87 |
severe errors to the log file. Open a second log file, turn on full |
| 88 |
debug logs in the "MySystem::Helpers::ScanDir" component and dump all |
| 89 |
messages originating from there into the new log file". And all this is |
| 90 |
possible by just changing the parameters in a configuration file, which |
| 91 |
your system can re-read even while it's running! |
| 92 |
|
| 93 |
How to use it |
| 94 |
The "Log::Log4perl" package can be initialized in two ways: Either via |
| 95 |
Perl commands or via a "log4j"-style configuration file. |
| 96 |
|
| 97 |
Initialize via a configuration file |
| 98 |
This is the easiest way to prepare your system for using |
| 99 |
"Log::Log4perl". Use a configuration file like this: |
| 100 |
|
| 101 |
############################################################ |
| 102 |
# A simple root logger with a Log::Log4perl::Appender::File |
| 103 |
# file appender in Perl. |
| 104 |
############################################################ |
| 105 |
log4perl.rootLogger=ERROR, LOGFILE |
| 106 |
|
| 107 |
log4perl.appender.LOGFILE=Log::Log4perl::Appender::File |
| 108 |
log4perl.appender.LOGFILE.filename=/var/log/myerrs.log |
| 109 |
log4perl.appender.LOGFILE.mode=append |
| 110 |
|
| 111 |
log4perl.appender.LOGFILE.layout=PatternLayout |
| 112 |
log4perl.appender.LOGFILE.layout.ConversionPattern=[%r] %F %L %c - %m%n |
| 113 |
|
| 114 |
These lines define your standard logger that's appending severe errors |
| 115 |
to "/var/log/myerrs.log", using the format |
| 116 |
|
| 117 |
[millisecs] source-filename line-number class - message newline |
| 118 |
|
| 119 |
Assuming that this configuration file is saved as "log.conf", you need |
| 120 |
to read it in the startup section of your code, using the following |
| 121 |
commands: |
| 122 |
|
| 123 |
use Log::Log4perl; |
| 124 |
Log::Log4perl->init("log.conf"); |
| 125 |
|
| 126 |
After that's done *somewhere* in the code, you can retrieve logger |
| 127 |
objects *anywhere* in the code. Note that there's no need to carry any |
| 128 |
logger references around with your functions and methods. You can get a |
| 129 |
logger anytime via a singleton mechanism: |
| 130 |
|
| 131 |
package My::MegaPackage; |
| 132 |
use Log::Log4perl; |
| 133 |
|
| 134 |
sub some_method { |
| 135 |
my($param) = @_; |
| 136 |
|
| 137 |
my $log = Log::Log4perl->get_logger("My::MegaPackage"); |
| 138 |
|
| 139 |
$log->debug("Debug message"); |
| 140 |
$log->info("Info message"); |
| 141 |
$log->error("Error message"); |
| 142 |
|
| 143 |
... |
| 144 |
} |
| 145 |
|
| 146 |
With the configuration file above, "Log::Log4perl" will write "Error |
| 147 |
message" to the specified log file, but won't do anything for the |
| 148 |
"debug()" and "info()" calls, because the log level has been set to |
| 149 |
"ERROR" for all components in the first line of configuration file shown |
| 150 |
above. |
| 151 |
|
| 152 |
Why "Log::Log4perl->get_logger" and not "Log::Log4perl->new"? We don't |
| 153 |
want to create a new object every time. Usually in OO-Programming, you |
| 154 |
create an object once and use the reference to it to call its methods. |
| 155 |
However, this requires that you pass around the object to all functions |
| 156 |
and the last thing we want is pollute each and every function/method |
| 157 |
we're using with a handle to the "Logger": |
| 158 |
|
| 159 |
sub function { # Brrrr!! |
| 160 |
my($logger, $some, $other, $parameters) = @_; |
| 161 |
} |
| 162 |
|
| 163 |
Instead, if a function/method wants a reference to the logger, it just |
| 164 |
calls the Logger's static "get_logger($category)" method to obtain a |
| 165 |
reference to the *one and only* possible logger object of a certain |
| 166 |
category. That's called a *singleton* if you're a Gamma fan. |
| 167 |
|
| 168 |
How does the logger know which messages it is supposed to log and which |
| 169 |
ones to suppress? "Log::Log4perl" works with inheritance: The config |
| 170 |
file above didn't specify anything about "My::MegaPackage". And yet, |
| 171 |
we've defined a logger of the category "My::MegaPackage". In this case, |
| 172 |
"Log::Log4perl" will walk up the namespace hierarchy ("My" and then |
| 173 |
we're at the root) to figure out if a log level is defined somewhere. In |
| 174 |
the case above, the log level at the root (root *always* defines a log |
| 175 |
level, but not necessarily an appender) defines that the log level is |
| 176 |
supposed to be "ERROR" -- meaning that *DEBUG* and *INFO* messages are |
| 177 |
suppressed. Note that this 'inheritance' is unrelated to Perl's class |
| 178 |
inheritance, it is merely related to the logger namespace. By the way, |
| 179 |
if you're ever in doubt about what a logger's category is, use |
| 180 |
"$logger->category()" to retrieve it. |
| 181 |
|
| 182 |
Log Levels |
| 183 |
There are six predefined log levels: "FATAL", "ERROR", "WARN", "INFO", |
| 184 |
"DEBUG", and "TRACE" (in descending priority). Your configured logging |
| 185 |
level has to at least match the priority of the logging message. |
| 186 |
|
| 187 |
If your configured logging level is "WARN", then messages logged with |
| 188 |
"info()", "debug()", and "trace()" will be suppressed. "fatal()", |
| 189 |
"error()" and "warn()" will make their way through, because their |
| 190 |
priority is higher or equal than the configured setting. |
| 191 |
|
| 192 |
Instead of calling the methods |
| 193 |
|
| 194 |
$logger->trace("..."); # Log a trace message |
| 195 |
$logger->debug("..."); # Log a debug message |
| 196 |
$logger->info("..."); # Log a info message |
| 197 |
$logger->warn("..."); # Log a warn message |
| 198 |
$logger->error("..."); # Log a error message |
| 199 |
$logger->fatal("..."); # Log a fatal message |
| 200 |
|
| 201 |
you could also call the "log()" method with the appropriate level using |
| 202 |
the constants defined in "Log::Log4perl::Level": |
| 203 |
|
| 204 |
use Log::Log4perl::Level; |
| 205 |
|
| 206 |
$logger->log($TRACE, "..."); |
| 207 |
$logger->log($DEBUG, "..."); |
| 208 |
$logger->log($INFO, "..."); |
| 209 |
$logger->log($WARN, "..."); |
| 210 |
$logger->log($ERROR, "..."); |
| 211 |
$logger->log($FATAL, "..."); |
| 212 |
|
| 213 |
This form is rarely used, but it comes in handy if you want to log at |
| 214 |
different levels depending on an exit code of a function: |
| 215 |
|
| 216 |
$logger->log( $exit_level{ $rc }, "..."); |
| 217 |
|
| 218 |
As for needing more logging levels than these predefined ones: It's |
| 219 |
usually best to steer your logging behaviour via the category mechanism |
| 220 |
instead. |
| 221 |
|
| 222 |
If you need to find out if the currently configured logging level would |
| 223 |
allow a logger's logging statement to go through, use the logger's |
| 224 |
"is_*level*()" methods: |
| 225 |
|
| 226 |
$logger->is_trace() # True if trace messages would go through |
| 227 |
$logger->is_debug() # True if debug messages would go through |
| 228 |
$logger->is_info() # True if info messages would go through |
| 229 |
$logger->is_warn() # True if warn messages would go through |
| 230 |
$logger->is_error() # True if error messages would go through |
| 231 |
$logger->is_fatal() # True if fatal messages would go through |
| 232 |
|
| 233 |
Example: "$logger->is_warn()" returns true if the logger's current |
| 234 |
level, as derived from either the logger's category (or, in absence of |
| 235 |
that, one of the logger's parent's level setting) is $WARN, $ERROR or |
| 236 |
$FATAL. |
| 237 |
|
| 238 |
Also available are a series of more Java-esque functions which return |
| 239 |
the same values. These are of the format "is*Level*Enabled()", so |
| 240 |
"$logger->isDebugEnabled()" is synonymous to "$logger->is_debug()". |
| 241 |
|
| 242 |
These level checking functions will come in handy later, when we want to |
| 243 |
block unnecessary expensive parameter construction in case the logging |
| 244 |
level is too low to log the statement anyway, like in: |
| 245 |
|
| 246 |
if($logger->is_error()) { |
| 247 |
$logger->error("Erroneous array: @super_long_array"); |
| 248 |
} |
| 249 |
|
| 250 |
If we had just written |
| 251 |
|
| 252 |
$logger->error("Erroneous array: @super_long_array"); |
| 253 |
|
| 254 |
then Perl would have interpolated @super_long_array into the string via |
| 255 |
an expensive operation only to figure out shortly after that the string |
| 256 |
can be ignored entirely because the configured logging level is lower |
| 257 |
than $ERROR. |
| 258 |
|
| 259 |
The to-be-logged message passed to all of the functions described above |
| 260 |
can consist of an arbitrary number of arguments, which the logging |
| 261 |
functions just chain together to a single string. Therefore |
| 262 |
|
| 263 |
$logger->debug("Hello ", "World", "!"); # and |
| 264 |
$logger->debug("Hello World!"); |
| 265 |
|
| 266 |
are identical. |
| 267 |
|
| 268 |
Note that even if one of the methods above returns true, it doesn't |
| 269 |
necessarily mean that the message will actually get logged. What |
| 270 |
is_debug() checks is that the logger used is configured to let a message |
| 271 |
of the given priority (DEBUG) through. But after this check, Log4perl |
| 272 |
will eventually apply custom filters and forward the message to one or |
| 273 |
more appenders. None of this gets checked by is_xxx(), for the simple |
| 274 |
reason that it's impossible to know what a custom filter does with a |
| 275 |
message without having the actual message or what an appender does to a |
| 276 |
message without actually having it log it. |
| 277 |
|
| 278 |
Log and die or warn |
| 279 |
Often, when you croak / carp / warn / die, you want to log those |
| 280 |
messages. Rather than doing the following: |
| 281 |
|
| 282 |
$logger->fatal($err) && die($err); |
| 283 |
|
| 284 |
you can use the following: |
| 285 |
|
| 286 |
$logger->logdie($err); |
| 287 |
|
| 288 |
And if instead of using |
| 289 |
|
| 290 |
warn($message); |
| 291 |
$logger->warn($message); |
| 292 |
|
| 293 |
to both issue a warning via Perl's warn() mechanism and make sure you |
| 294 |
have the same message in the log file as well, use: |
| 295 |
|
| 296 |
$logger->logwarn($message); |
| 297 |
|
| 298 |
Since there is an ERROR level between WARN and FATAL, there are two |
| 299 |
additional helper functions in case you'd like to use ERROR for either |
| 300 |
warn() or die(): |
| 301 |
|
| 302 |
$logger->error_warn(); |
| 303 |
$logger->error_die(); |
| 304 |
|
| 305 |
Finally, there's the Carp functions that, in addition to logging, also |
| 306 |
pass the stringified message to their companions in the Carp package: |
| 307 |
|
| 308 |
$logger->logcarp(); # warn w/ 1-level stack trace |
| 309 |
$logger->logcluck(); # warn w/ full stack trace |
| 310 |
$logger->logcroak(); # die w/ 1-level stack trace |
| 311 |
$logger->logconfess(); # die w/ full stack trace |
| 312 |
|
| 313 |
Appenders |
| 314 |
If you don't define any appenders, nothing will happen. Appenders will |
| 315 |
be triggered whenever the configured logging level requires a message to |
| 316 |
be logged and not suppressed. |
| 317 |
|
| 318 |
"Log::Log4perl" doesn't define any appenders by default, not even the |
| 319 |
root logger has one. |
| 320 |
|
| 321 |
"Log::Log4perl" already comes with a standard set of appenders: |
| 322 |
|
| 323 |
Log::Log4perl::Appender::Screen |
| 324 |
Log::Log4perl::Appender::ScreenColoredLevels |
| 325 |
Log::Log4perl::Appender::File |
| 326 |
Log::Log4perl::Appender::Socket |
| 327 |
Log::Log4perl::Appender::DBI |
| 328 |
Log::Log4perl::Appender::Synchronized |
| 329 |
Log::Log4perl::Appender::RRDs |
| 330 |
|
| 331 |
to log to the screen, to files and to databases. |
| 332 |
|
| 333 |
On CPAN, you can find additional appenders like |
| 334 |
|
| 335 |
Log::Log4perl::Layout::XMLLayout |
| 336 |
|
| 337 |
by Guido Carls <[email protected]>. It allows for hooking up Log::Log4perl |
| 338 |
with the graphical Log Analyzer Chainsaw (see "Can I use Log::Log4perl |
| 339 |
with log4j's Chainsaw?" in Log::Log4perl::FAQ). |
| 340 |
|
| 341 |
Additional Appenders via Log::Dispatch |
| 342 |
"Log::Log4perl" also supports *Dave Rolskys* excellent "Log::Dispatch" |
| 343 |
framework which implements a wide variety of different appenders. |
| 344 |
|
| 345 |
Here's the list of appender modules currently available via |
| 346 |
"Log::Dispatch": |
| 347 |
|
| 348 |
Log::Dispatch::ApacheLog |
| 349 |
Log::Dispatch::DBI (by Tatsuhiko Miyagawa) |
| 350 |
Log::Dispatch::Email, |
| 351 |
Log::Dispatch::Email::MailSend, |
| 352 |
Log::Dispatch::Email::MailSendmail, |
| 353 |
Log::Dispatch::Email::MIMELite |
| 354 |
Log::Dispatch::File |
| 355 |
Log::Dispatch::FileRotate (by Mark Pfeiffer) |
| 356 |
Log::Dispatch::Handle |
| 357 |
Log::Dispatch::Screen |
| 358 |
Log::Dispatch::Syslog |
| 359 |
Log::Dispatch::Tk (by Dominique Dumont) |
| 360 |
|
| 361 |
Please note that in order to use any of these additional appenders, you |
| 362 |
have to fetch Log::Dispatch from CPAN and install it. Also the |
| 363 |
particular appender you're using might require installing the particular |
| 364 |
module. |
| 365 |
|
| 366 |
For additional information on appenders, please check the |
| 367 |
Log::Log4perl::Appender manual page. |
| 368 |
|
| 369 |
Appender Example |
| 370 |
Now let's assume that we want to log "info()" or higher prioritized |
| 371 |
messages in the "Foo::Bar" category to both STDOUT and to a log file, |
| 372 |
say "test.log". In the initialization section of your system, just |
| 373 |
define two appenders using the readily available |
| 374 |
"Log::Log4perl::Appender::File" and "Log::Log4perl::Appender::Screen" |
| 375 |
modules: |
| 376 |
|
| 377 |
use Log::Log4perl; |
| 378 |
|
| 379 |
# Configuration in a string ... |
| 380 |
my $conf = q( |
| 381 |
log4perl.category.Foo.Bar = INFO, Logfile, Screen |
| 382 |
|
| 383 |
log4perl.appender.Logfile = Log::Log4perl::Appender::File |
| 384 |
log4perl.appender.Logfile.filename = test.log |
| 385 |
log4perl.appender.Logfile.layout = Log::Log4perl::Layout::PatternLayout |
| 386 |
log4perl.appender.Logfile.layout.ConversionPattern = [%r] %F %L %m%n |
| 387 |
|
| 388 |
log4perl.appender.Screen = Log::Log4perl::Appender::Screen |
| 389 |
log4perl.appender.Screen.stderr = 0 |
| 390 |
log4perl.appender.Screen.layout = Log::Log4perl::Layout::SimpleLayout |
| 391 |
); |
| 392 |
|
| 393 |
# ... passed as a reference to init() |
| 394 |
Log::Log4perl::init( \$conf ); |
| 395 |
|
| 396 |
Once the initialization shown above has happened once, typically in the |
| 397 |
startup code of your system, just use the defined logger anywhere in |
| 398 |
your system: |
| 399 |
|
| 400 |
########################## |
| 401 |
# ... in some function ... |
| 402 |
########################## |
| 403 |
my $log = Log::Log4perl::get_logger("Foo::Bar"); |
| 404 |
|
| 405 |
# Logs both to STDOUT and to the file test.log |
| 406 |
$log->info("Important Info!"); |
| 407 |
|
| 408 |
The "layout" settings specified in the configuration section define the |
| 409 |
format in which the message is going to be logged by the specified |
| 410 |
appender. The format shown for the file appender is logging not only the |
| 411 |
message but also the number of milliseconds since the program has |
| 412 |
started (%r), the name of the file the call to the logger has happened |
| 413 |
and the line number there (%F and %L), the message itself (%m) and a |
| 414 |
OS-specific newline character (%n): |
| 415 |
|
| 416 |
[187] ./myscript.pl 27 Important Info! |
| 417 |
|
| 418 |
The screen appender above, on the other hand, uses a "SimpleLayout", |
| 419 |
which logs the debug level, a hyphen (-) and the log message: |
| 420 |
|
| 421 |
INFO - Important Info! |
| 422 |
|
| 423 |
For more detailed info on layout formats, see "Log Layouts". |
| 424 |
|
| 425 |
In the configuration sample above, we chose to define a *category* |
| 426 |
logger ("Foo::Bar"). This will cause only messages originating from this |
| 427 |
specific category logger to be logged in the defined format and |
| 428 |
locations. |
| 429 |
|
| 430 |
Logging newlines |
| 431 |
There's some controversy between different logging systems as to when |
| 432 |
and where newlines are supposed to be added to logged messages. |
| 433 |
|
| 434 |
The Log4perl way is that a logging statement *should not* contain a |
| 435 |
newline: |
| 436 |
|
| 437 |
$logger->info("Some message"); |
| 438 |
$logger->info("Another message"); |
| 439 |
|
| 440 |
If this is supposed to end up in a log file like |
| 441 |
|
| 442 |
Some message |
| 443 |
Another message |
| 444 |
|
| 445 |
then an appropriate appender layout like "%m%n" will take care of adding |
| 446 |
a newline at the end of each message to make sure every message is |
| 447 |
printed on its own line. |
| 448 |
|
| 449 |
Other logging systems, Log::Dispatch in particular, recommend adding the |
| 450 |
newline to the log statement. This doesn't work well, however, if you, |
| 451 |
say, replace your file appender by a database appender, and all of a |
| 452 |
sudden those newlines scattered around the code don't make sense |
| 453 |
anymore. |
| 454 |
|
| 455 |
Assigning matching layouts to different appenders and leaving newlines |
| 456 |
out of the code solves this problem. If you inherited code that has |
| 457 |
logging statements with newlines and want to make it work with Log4perl, |
| 458 |
read the Log::Log4perl::Layout::PatternLayout documentation on how to |
| 459 |
accomplish that. |
| 460 |
|
| 461 |
Configuration files |
| 462 |
As shown above, you can define "Log::Log4perl" loggers both from within |
| 463 |
your Perl code or from configuration files. The latter have the |
| 464 |
unbeatable advantage that you can modify your system's logging behaviour |
| 465 |
without interfering with the code at all. So even if your code is being |
| 466 |
run by somebody who's totally oblivious to Perl, they still can adapt |
| 467 |
the module's logging behaviour to their needs. |
| 468 |
|
| 469 |
"Log::Log4perl" has been designed to understand "Log4j" configuration |
| 470 |
files -- as used by the original Java implementation. Instead of |
| 471 |
reiterating the format description in [2], let me just list three |
| 472 |
examples (also derived from [2]), which should also illustrate how it |
| 473 |
works: |
| 474 |
|
| 475 |
log4j.rootLogger=DEBUG, A1 |
| 476 |
log4j.appender.A1=org.apache.log4j.ConsoleAppender |
| 477 |
log4j.appender.A1.layout=org.apache.log4j.PatternLayout |
| 478 |
log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c %x - %m%n |
| 479 |
|
| 480 |
This enables messages of priority "DEBUG" or higher in the root |
| 481 |
hierarchy and has the system write them to the console. |
| 482 |
"ConsoleAppender" is a Java appender, but "Log::Log4perl" jumps through |
| 483 |
a significant number of hoops internally to map these to their |
| 484 |
corresponding Perl classes, "Log::Log4perl::Appender::Screen" in this |
| 485 |
case. |
| 486 |
|
| 487 |
Second example: |
| 488 |
|
| 489 |
log4perl.rootLogger=DEBUG, A1 |
| 490 |
log4perl.appender.A1=Log::Log4perl::Appender::Screen |
| 491 |
log4perl.appender.A1.layout=PatternLayout |
| 492 |
log4perl.appender.A1.layout.ConversionPattern=%d %-5p %c - %m%n |
| 493 |
log4perl.logger.com.foo=WARN |
| 494 |
|
| 495 |
This defines two loggers: The root logger and the "com.foo" logger. The |
| 496 |
root logger is easily triggered by debug-messages, but the "com.foo" |
| 497 |
logger makes sure that messages issued within the "Com::Foo" component |
| 498 |
and below are only forwarded to the appender if they're of priority |
| 499 |
*warning* or higher. |
| 500 |
|
| 501 |
Note that the "com.foo" logger doesn't define an appender. Therefore, it |
| 502 |
will just propagate the message up the hierarchy until the root logger |
| 503 |
picks it up and forwards it to the one and only appender of the root |
| 504 |
category, using the format defined for it. |
| 505 |
|
| 506 |
Third example: |
| 507 |
|
| 508 |
log4j.rootLogger=DEBUG, stdout, R |
| 509 |
log4j.appender.stdout=org.apache.log4j.ConsoleAppender |
| 510 |
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout |
| 511 |
log4j.appender.stdout.layout.ConversionPattern=%5p (%F:%L) - %m%n |
| 512 |
log4j.appender.R=org.apache.log4j.RollingFileAppender |
| 513 |
log4j.appender.R.File=example.log |
| 514 |
log4j.appender.R.layout=org.apache.log4j.PatternLayout |
| 515 |
log4j.appender.R.layout.ConversionPattern=%p %c - %m%n |
| 516 |
|
| 517 |
The root logger defines two appenders here: "stdout", which uses |
| 518 |
"org.apache.log4j.ConsoleAppender" (ultimately mapped by "Log::Log4perl" |
| 519 |
to Log::Log4perl::Appender::Screen) to write to the screen. And "R", a |
| 520 |
"org.apache.log4j.RollingFileAppender" (mapped by "Log::Log4perl" to |
| 521 |
Log::Dispatch::FileRotate with the "File" attribute specifying the log |
| 522 |
file. |
| 523 |
|
| 524 |
See Log::Log4perl::Config for more examples and syntax explanations. |
| 525 |
|
| 526 |
Log Layouts |
| 527 |
If the logging engine passes a message to an appender, because it thinks |
| 528 |
it should be logged, the appender doesn't just write it out haphazardly. |
| 529 |
There's ways to tell the appender how to format the message and add all |
| 530 |
sorts of interesting data to it: The date and time when the event |
| 531 |
happened, the file, the line number, the debug level of the logger and |
| 532 |
others. |
| 533 |
|
| 534 |
There's currently two layouts defined in "Log::Log4perl": |
| 535 |
"Log::Log4perl::Layout::SimpleLayout" and |
| 536 |
"Log::Log4perl::Layout::PatternLayout": |
| 537 |
|
| 538 |
"Log::Log4perl::SimpleLayout" |
| 539 |
formats a message in a simple way and just prepends it by the debug |
| 540 |
level and a hyphen: ""$level - $message", for example "FATAL - Can't |
| 541 |
open password file". |
| 542 |
|
| 543 |
"Log::Log4perl::Layout::PatternLayout" |
| 544 |
on the other hand is very powerful and allows for a very flexible |
| 545 |
format in "printf"-style. The format string can contain a number of |
| 546 |
placeholders which will be replaced by the logging engine when it's |
| 547 |
time to log the message: |
| 548 |
|
| 549 |
%c Category of the logging event. |
| 550 |
%C Fully qualified package (or class) name of the caller |
| 551 |
%d Current date in yyyy/MM/dd HH:mm:ss format |
| 552 |
%F File where the logging event occurred |
| 553 |
%H Hostname (if Sys::Hostname is available) |
| 554 |
%l Fully qualified name of the calling method followed by the |
| 555 |
callers source the file name and line number between |
| 556 |
parentheses. |
| 557 |
%L Line number within the file where the log statement was issued |
| 558 |
%m The message to be logged |
| 559 |
%m{chomp} The message to be logged, stripped off a trailing newline |
| 560 |
%M Method or function where the logging request was issued |
| 561 |
%n Newline (OS-independent) |
| 562 |
%p Priority of the logging event (AKA log level) |
| 563 |
%P pid of the current process |
| 564 |
%r Number of milliseconds elapsed from program start to logging |
| 565 |
event |
| 566 |
%R Number of milliseconds elapsed from last logging event to |
| 567 |
current logging event |
| 568 |
%T A stack trace of functions called |
| 569 |
%x The topmost NDC (see below) |
| 570 |
%X{key} The entry 'key' of the MDC (see below) |
| 571 |
%% A literal percent (%) sign |
| 572 |
|
| 573 |
NDC and MDC are explained in "Nested Diagnostic Context (NDC)" and |
| 574 |
"Mapped Diagnostic Context (MDC)". |
| 575 |
|
| 576 |
Also, %d can be fine-tuned to display only certain characteristics |
| 577 |
of a date, according to the SimpleDateFormat in the Java World |
| 578 |
(<https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/ |
| 579 |
text/SimpleDateFormat.html>) |
| 580 |
|
| 581 |
In this way, %d{HH:mm} displays only hours and minutes of the |
| 582 |
current date, while %d{yy, EEEE} displays a two-digit year, followed |
| 583 |
by a spelled-out day (like "Wednesday"). |
| 584 |
|
| 585 |
Similar options are available for shrinking the displayed category |
| 586 |
or limit file/path components, %F{1} only displays the source file |
| 587 |
*name* without any path components while %F logs the full path. |
| 588 |
%c{2} only logs the last two components of the current category, |
| 589 |
"Foo::Bar::Baz" becomes "Bar::Baz" and saves space. |
| 590 |
|
| 591 |
If those placeholders aren't enough, then you can define your own |
| 592 |
right in the config file like this: |
| 593 |
|
| 594 |
log4perl.PatternLayout.cspec.U = sub { return "UID $<" } |
| 595 |
|
| 596 |
See Log::Log4perl::Layout::PatternLayout for further details on |
| 597 |
customized specifiers. |
| 598 |
|
| 599 |
Please note that the subroutines you're defining in this way are |
| 600 |
going to be run in the "main" namespace, so be sure to fully qualify |
| 601 |
functions and variables if they're located in different packages. |
| 602 |
|
| 603 |
SECURITY NOTE: this feature means arbitrary perl code can be |
| 604 |
embedded in the config file. In the rare case where the people who |
| 605 |
have access to your config file are different from the people who |
| 606 |
write your code and shouldn't have execute rights, you might want to |
| 607 |
call |
| 608 |
|
| 609 |
Log::Log4perl::Config->allow_code(0); |
| 610 |
|
| 611 |
before you call init(). Alternatively you can supply a restricted |
| 612 |
set of Perl opcodes that can be embedded in the config file as |
| 613 |
described in "Restricting what Opcodes can be in a Perl Hook". |
| 614 |
|
| 615 |
All placeholders are quantifiable, just like in *printf*. Following this |
| 616 |
tradition, "%-20c" will reserve 20 chars for the category and |
| 617 |
left-justify it. |
| 618 |
|
| 619 |
For more details on logging and how to use the flexible and the simple |
| 620 |
format, check out the original "log4j" website under |
| 621 |
|
| 622 |
SimpleLayout |
| 623 |
<http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/SimpleLayo |
| 624 |
ut.html> and PatternLayout |
| 625 |
<http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLay |
| 626 |
out.html> |
| 627 |
|
| 628 |
Penalties |
| 629 |
Logging comes with a price tag. "Log::Log4perl" has been optimized to |
| 630 |
allow for maximum performance, both with logging enabled and disabled. |
| 631 |
|
| 632 |
But you need to be aware that there's a small hit every time your code |
| 633 |
encounters a log statement -- no matter if logging is enabled or not. |
| 634 |
"Log::Log4perl" has been designed to keep this so low that it will be |
| 635 |
unnoticeable to most applications. |
| 636 |
|
| 637 |
Here's a couple of tricks which help "Log::Log4perl" to avoid |
| 638 |
unnecessary delays: |
| 639 |
|
| 640 |
You can save serious time if you're logging something like |
| 641 |
|
| 642 |
# Expensive in non-debug mode! |
| 643 |
for (@super_long_array) { |
| 644 |
$logger->debug("Element: $_"); |
| 645 |
} |
| 646 |
|
| 647 |
and @super_long_array is fairly big, so looping through it is pretty |
| 648 |
expensive. Only you, the programmer, knows that going through that "for" |
| 649 |
loop can be skipped entirely if the current logging level for the actual |
| 650 |
component is higher than "debug". In this case, use this instead: |
| 651 |
|
| 652 |
# Cheap in non-debug mode! |
| 653 |
if($logger->is_debug()) { |
| 654 |
for (@super_long_array) { |
| 655 |
$logger->debug("Element: $_"); |
| 656 |
} |
| 657 |
} |
| 658 |
|
| 659 |
If you're afraid that generating the parameters to the logging function |
| 660 |
is fairly expensive, use closures: |
| 661 |
|
| 662 |
# Passed as subroutine ref |
| 663 |
use Data::Dumper; |
| 664 |
$logger->debug(sub { Dumper($data) } ); |
| 665 |
|
| 666 |
This won't unravel $data via Dumper() unless it's actually needed |
| 667 |
because it's logged. |
| 668 |
|
| 669 |
Also, Log::Log4perl lets you specify arguments to logger functions in |
| 670 |
*message output filter syntax*: |
| 671 |
|
| 672 |
$logger->debug("Structure: ", |
| 673 |
{ filter => \&Dumper, |
| 674 |
value => $someref }); |
| 675 |
|
| 676 |
In this way, shortly before Log::Log4perl sending the message out to any |
| 677 |
appenders, it will be searching all arguments for hash references and |
| 678 |
treat them in a special way: |
| 679 |
|
| 680 |
It will invoke the function given as a reference with the "filter" key |
| 681 |
("Data::Dumper::Dumper()") and pass it the value that came with the key |
| 682 |
named "value" as an argument. The anonymous hash in the call above will |
| 683 |
be replaced by the return value of the filter function. |
| 684 |
|
| 685 |
Categories |
| 686 |
Categories are also called "Loggers" in Log4perl, both refer to the same |
| 687 |
thing and these terms are used interchangeably. "Log::Log4perl" uses |
| 688 |
*categories* to determine if a log statement in a component should be |
| 689 |
executed or suppressed at the current logging level. Most of the time, |
| 690 |
these categories are just the classes the log statements are located in: |
| 691 |
|
| 692 |
package Candy::Twix; |
| 693 |
|
| 694 |
sub new { |
| 695 |
my $logger = Log::Log4perl->get_logger("Candy::Twix"); |
| 696 |
$logger->debug("Creating a new Twix bar"); |
| 697 |
bless {}, shift; |
| 698 |
} |
| 699 |
|
| 700 |
# ... |
| 701 |
|
| 702 |
package Candy::Snickers; |
| 703 |
|
| 704 |
sub new { |
| 705 |
my $logger = Log::Log4perl->get_logger("Candy.Snickers"); |
| 706 |
$logger->debug("Creating a new Snickers bar"); |
| 707 |
bless {}, shift; |
| 708 |
} |
| 709 |
|
| 710 |
# ... |
| 711 |
|
| 712 |
package main; |
| 713 |
Log::Log4perl->init("mylogdefs.conf"); |
| 714 |
|
| 715 |
# => "LOG> Creating a new Snickers bar" |
| 716 |
my $first = Candy::Snickers->new(); |
| 717 |
# => "LOG> Creating a new Twix bar" |
| 718 |
my $second = Candy::Twix->new(); |
| 719 |
|
| 720 |
Note that you can separate your category hierarchy levels using either |
| 721 |
dots like in Java (.) or double-colons (::) like in Perl. Both notations |
| 722 |
are equivalent and are handled the same way internally. |
| 723 |
|
| 724 |
However, categories are just there to make use of inheritance: if you |
| 725 |
invoke a logger in a sub-category, it will bubble up the hierarchy and |
| 726 |
call the appropriate appenders. Internally, categories are not related |
| 727 |
to the class hierarchy of the program at all -- they're purely virtual. |
| 728 |
You can use arbitrary categories -- for example in the following |
| 729 |
program, which isn't oo-style, but procedural: |
| 730 |
|
| 731 |
sub print_portfolio { |
| 732 |
|
| 733 |
my $log = Log::Log4perl->get_logger("user.portfolio"); |
| 734 |
$log->debug("Quotes requested: @_"); |
| 735 |
|
| 736 |
for(@_) { |
| 737 |
print "$_: ", get_quote($_), "\n"; |
| 738 |
} |
| 739 |
} |
| 740 |
|
| 741 |
sub get_quote { |
| 742 |
|
| 743 |
my $log = Log::Log4perl->get_logger("internet.quotesystem"); |
| 744 |
$log->debug("Fetching quote: $_[0]"); |
| 745 |
|
| 746 |
return yahoo_quote($_[0]); |
| 747 |
} |
| 748 |
|
| 749 |
The logger in first function, "print_portfolio", is assigned the |
| 750 |
(virtual) "user.portfolio" category. Depending on the "Log4perl" |
| 751 |
configuration, this will either call a "user.portfolio" appender, a |
| 752 |
"user" appender, or an appender assigned to root -- without |
| 753 |
"user.portfolio" having any relevance to the class system used in the |
| 754 |
program. The logger in the second function adheres to the |
| 755 |
"internet.quotesystem" category -- again, maybe because it's bundled |
| 756 |
with other Internet functions, but not because there would be a class of |
| 757 |
this name somewhere. |
| 758 |
|
| 759 |
However, be careful, don't go overboard: if you're developing a system |
| 760 |
in object-oriented style, using the class hierarchy is usually your best |
| 761 |
choice. Think about the people taking over your code one day: The class |
| 762 |
hierarchy is probably what they know right up front, so it's easy for |
| 763 |
them to tune the logging to their needs. |
| 764 |
|
| 765 |
Turn off a component |
| 766 |
"Log4perl" doesn't only allow you to selectively switch *on* a category |
| 767 |
of log messages, you can also use the mechanism to selectively *disable* |
| 768 |
logging in certain components whereas logging is kept turned on in |
| 769 |
higher-level categories. This mechanism comes in handy if you find that |
| 770 |
while bumping up the logging level of a high-level (i. e. close to root) |
| 771 |
category, that one component logs more than it should, |
| 772 |
|
| 773 |
Here's how it works: |
| 774 |
|
| 775 |
############################################################ |
| 776 |
# Turn off logging in a lower-level category while keeping |
| 777 |
# it active in higher-level categories. |
| 778 |
############################################################ |
| 779 |
log4perl.rootLogger=DEBUG, LOGFILE |
| 780 |
log4perl.logger.deep.down.the.hierarchy = ERROR, LOGFILE |
| 781 |
|
| 782 |
# ... Define appenders ... |
| 783 |
|
| 784 |
This way, log messages issued from within "Deep::Down::The::Hierarchy" |
| 785 |
and below will be logged only if they're "ERROR" or worse, while in all |
| 786 |
other system components even "DEBUG" messages will be logged. |
| 787 |
|
| 788 |
Return Values |
| 789 |
All logging methods return values indicating if their message actually |
| 790 |
reached one or more appenders. If the message has been suppressed |
| 791 |
because of level constraints, "undef" is returned. |
| 792 |
|
| 793 |
For example, |
| 794 |
|
| 795 |
my $ret = $logger->info("Message"); |
| 796 |
|
| 797 |
will return "undef" if the system debug level for the current category |
| 798 |
is not "INFO" or more permissive. If Log::Log4perl forwarded the message |
| 799 |
to one or more appenders, the number of appenders is returned. |
| 800 |
|
| 801 |
If appenders decide to veto on the message with an appender threshold, |
| 802 |
the log method's return value will have them excluded. This means that |
| 803 |
if you've got one appender holding an appender threshold and you're |
| 804 |
logging a message which passes the system's log level hurdle but not the |
| 805 |
appender threshold, 0 will be returned by the log function. |
| 806 |
|
| 807 |
The bottom line is: Logging functions will return a *true* value if the |
| 808 |
message made it through to one or more appenders and a *false* value if |
| 809 |
it didn't. This allows for constructs like |
| 810 |
|
| 811 |
$logger->fatal("@_") or print STDERR "@_\n"; |
| 812 |
|
| 813 |
which will ensure that the fatal message isn't lost if the current level |
| 814 |
is lower than FATAL or printed twice if the level is acceptable but an |
| 815 |
appender already points to STDERR. |
| 816 |
|
| 817 |
Pitfalls with Categories |
| 818 |
Be careful with just blindly reusing the system's packages as |
| 819 |
categories. If you do, you'll get into trouble with inherited methods. |
| 820 |
Imagine the following class setup: |
| 821 |
|
| 822 |
use Log::Log4perl; |
| 823 |
|
| 824 |
########################################### |
| 825 |
package Bar; |
| 826 |
########################################### |
| 827 |
sub new { |
| 828 |
my($class) = @_; |
| 829 |
my $logger = Log::Log4perl::get_logger(__PACKAGE__); |
| 830 |
$logger->debug("Creating instance"); |
| 831 |
bless {}, $class; |
| 832 |
} |
| 833 |
########################################### |
| 834 |
package Bar::Twix; |
| 835 |
########################################### |
| 836 |
our @ISA = qw(Bar); |
| 837 |
|
| 838 |
########################################### |
| 839 |
package main; |
| 840 |
########################################### |
| 841 |
Log::Log4perl->init(\ qq{ |
| 842 |
log4perl.category.Bar.Twix = DEBUG, Screen |
| 843 |
log4perl.appender.Screen = Log::Log4perl::Appender::Screen |
| 844 |
log4perl.appender.Screen.layout = SimpleLayout |
| 845 |
}); |
| 846 |
|
| 847 |
my $bar = Bar::Twix->new(); |
| 848 |
|
| 849 |
"Bar::Twix" just inherits everything from "Bar", including the |
| 850 |
constructor "new()". Contrary to what you might be thinking at first, |
| 851 |
this won't log anything. Reason for this is the "get_logger()" call in |
| 852 |
package "Bar", which will always get a logger of the "Bar" category, |
| 853 |
even if we call "new()" via the "Bar::Twix" package, which will make |
| 854 |
perl go up the inheritance tree to actually execute "Bar::new()". Since |
| 855 |
we've only defined logging behaviour for "Bar::Twix" in the |
| 856 |
configuration file, nothing will happen. |
| 857 |
|
| 858 |
This can be fixed by changing the "get_logger()" method in "Bar::new()" |
| 859 |
to obtain a logger of the category matching the *actual* class of the |
| 860 |
object, like in |
| 861 |
|
| 862 |
# ... in Bar::new() ... |
| 863 |
my $logger = Log::Log4perl::get_logger( $class ); |
| 864 |
|
| 865 |
In a method other than the constructor, the class name of the actual |
| 866 |
object can be obtained by calling "ref()" on the object reference, so |
| 867 |
|
| 868 |
package BaseClass; |
| 869 |
use Log::Log4perl qw( get_logger ); |
| 870 |
|
| 871 |
sub new { |
| 872 |
bless {}, shift; |
| 873 |
} |
| 874 |
|
| 875 |
sub method { |
| 876 |
my( $self ) = @_; |
| 877 |
|
| 878 |
get_logger( ref $self )->debug( "message" ); |
| 879 |
} |
| 880 |
|
| 881 |
package SubClass; |
| 882 |
our @ISA = qw(BaseClass); |
| 883 |
|
| 884 |
is the recommended pattern to make sure that |
| 885 |
|
| 886 |
my $sub = SubClass->new(); |
| 887 |
$sub->meth(); |
| 888 |
|
| 889 |
starts logging if the "SubClass" category (and not the "BaseClass" |
| 890 |
category has logging enabled at the DEBUG level. |
| 891 |
|
| 892 |
Initialize once and only once |
| 893 |
It's important to realize that Log::Log4perl gets initialized once and |
| 894 |
only once, typically at the start of a program or system. Calling |
| 895 |
"init()" more than once will cause it to clobber the existing |
| 896 |
configuration and *replace* it by the new one. |
| 897 |
|
| 898 |
If you're in a traditional CGI environment, where every request is |
| 899 |
handled by a new process, calling "init()" every time is fine. In |
| 900 |
persistent environments like "mod_perl", however, Log::Log4perl should |
| 901 |
be initialized either at system startup time (Apache offers startup |
| 902 |
handlers for that) or via |
| 903 |
|
| 904 |
# Init or skip if already done |
| 905 |
Log::Log4perl->init_once($conf_file); |
| 906 |
|
| 907 |
"init_once()" is identical to "init()", just with the exception that it |
| 908 |
will leave a potentially existing configuration alone and will only call |
| 909 |
"init()" if Log::Log4perl hasn't been initialized yet. |
| 910 |
|
| 911 |
If you're just curious if Log::Log4perl has been initialized yet, the |
| 912 |
check |
| 913 |
|
| 914 |
if(Log::Log4perl->initialized()) { |
| 915 |
# Yes, Log::Log4perl has already been initialized |
| 916 |
} else { |
| 917 |
# No, not initialized yet ... |
| 918 |
} |
| 919 |
|
| 920 |
can be used. |
| 921 |
|
| 922 |
If you're afraid that the components of your system are stepping on each |
| 923 |
other's toes or if you are thinking that different components should |
| 924 |
initialize Log::Log4perl separately, try to consolidate your system to |
| 925 |
use a centralized Log4perl configuration file and use Log4perl's |
| 926 |
*categories* to separate your components. |
| 927 |
|
| 928 |
Custom Filters |
| 929 |
Log4perl allows the use of customized filters in its appenders to |
| 930 |
control the output of messages. These filters might grep for certain |
| 931 |
text chunks in a message, verify that its priority matches or exceeds a |
| 932 |
certain level or that this is the 10th time the same message has been |
| 933 |
submitted -- and come to a log/no log decision based upon these |
| 934 |
circumstantial facts. |
| 935 |
|
| 936 |
Check out Log::Log4perl::Filter for detailed instructions on how to use |
| 937 |
them. |
| 938 |
|
| 939 |
Performance |
| 940 |
The performance of Log::Log4perl calls obviously depends on a lot of |
| 941 |
things. But to give you a general idea, here's some rough numbers: |
| 942 |
|
| 943 |
On a Pentium 4 Linux box at 2.4 GHz, you'll get through |
| 944 |
|
| 945 |
* 500,000 suppressed log statements per second |
| 946 |
|
| 947 |
* 30,000 logged messages per second (using an in-memory appender) |
| 948 |
|
| 949 |
* init_and_watch delay mode: 300,000 suppressed, 30,000 logged. |
| 950 |
init_and_watch signal mode: 450,000 suppressed, 30,000 logged. |
| 951 |
|
| 952 |
Numbers depend on the complexity of the Log::Log4perl configuration. For |
| 953 |
a more detailed benchmark test, check the "docs/benchmark.results.txt" |
| 954 |
document in the Log::Log4perl distribution. |
| 955 |
|
| 956 |
Cool Tricks |
| 957 |
Here's a collection of useful tricks for the advanced "Log::Log4perl" |
| 958 |
user. For more, check the FAQ, either in the distribution |
| 959 |
(Log::Log4perl::FAQ) or on <http://log4perl.sourceforge.net>. |
| 960 |
|
| 961 |
Shortcuts |
| 962 |
When getting an instance of a logger, instead of saying |
| 963 |
|
| 964 |
use Log::Log4perl; |
| 965 |
my $logger = Log::Log4perl->get_logger(); |
| 966 |
|
| 967 |
it's often more convenient to import the "get_logger" method from |
| 968 |
"Log::Log4perl" into the current namespace: |
| 969 |
|
| 970 |
use Log::Log4perl qw(get_logger); |
| 971 |
my $logger = get_logger(); |
| 972 |
|
| 973 |
Please note this difference: To obtain the root logger, please use |
| 974 |
"get_logger("")", call it without parameters ("get_logger()"), you'll |
| 975 |
get the logger of a category named after the current package. |
| 976 |
"get_logger()" is equivalent to "get_logger(__PACKAGE__)". |
| 977 |
|
| 978 |
Alternative initialization |
| 979 |
Instead of having "init()" read in a configuration file by specifying a |
| 980 |
file name or passing it a reference to an open filehandle |
| 981 |
("Log::Log4perl->init( \*FILE )"), you can also pass in a reference to a |
| 982 |
string, containing the content of the file: |
| 983 |
|
| 984 |
Log::Log4perl->init( \$config_text ); |
| 985 |
|
| 986 |
Also, if you've got the "name=value" pairs of the configuration in a |
| 987 |
hash, you can just as well initialize "Log::Log4perl" with a reference |
| 988 |
to it: |
| 989 |
|
| 990 |
my %key_value_pairs = ( |
| 991 |
"log4perl.rootLogger" => "ERROR, LOGFILE", |
| 992 |
"log4perl.appender.LOGFILE" => "Log::Log4perl::Appender::File", |
| 993 |
... |
| 994 |
); |
| 995 |
|
| 996 |
Log::Log4perl->init( \%key_value_pairs ); |
| 997 |
|
| 998 |
Or also you can use a URL, see below: |
| 999 |
|
| 1000 |
Using LWP to parse URLs |
| 1001 |
(This section borrowed from XML::DOM::Parser by T.J. Mather). |
| 1002 |
|
| 1003 |
The init() function now also supports URLs, e.g. |
| 1004 |
*http://www.erols.com/enno/xsa.xml*. It uses LWP to download the file |
| 1005 |
and then calls parse() on the resulting string. By default it will use a |
| 1006 |
LWP::UserAgent that is created as follows: |
| 1007 |
|
| 1008 |
use LWP::UserAgent; |
| 1009 |
$LWP_USER_AGENT = LWP::UserAgent->new; |
| 1010 |
$LWP_USER_AGENT->env_proxy; |
| 1011 |
|
| 1012 |
Note that env_proxy reads proxy settings from environment variables, |
| 1013 |
which is what Log4perl needs to do to get through our firewall. If you |
| 1014 |
want to use a different LWP::UserAgent, you can set it with |
| 1015 |
|
| 1016 |
Log::Log4perl::Config::set_LWP_UserAgent($my_agent); |
| 1017 |
|
| 1018 |
Currently, LWP is used when the filename (passed to parsefile) starts |
| 1019 |
with one of the following URL schemes: http, https, ftp, wais, gopher, |
| 1020 |
or file (followed by a colon.) |
| 1021 |
|
| 1022 |
Don't use this feature with init_and_watch(). |
| 1023 |
|
| 1024 |
Automatic reloading of changed configuration files |
| 1025 |
Instead of just statically initializing Log::Log4perl via |
| 1026 |
|
| 1027 |
Log::Log4perl->init($conf_file); |
| 1028 |
|
| 1029 |
there's a way to have Log::Log4perl periodically check for changes in |
| 1030 |
the configuration and reload it if necessary: |
| 1031 |
|
| 1032 |
Log::Log4perl->init_and_watch($conf_file, $delay); |
| 1033 |
|
| 1034 |
In this mode, Log::Log4perl will examine the configuration file |
| 1035 |
$conf_file every $delay seconds for changes via the file's last |
| 1036 |
modification timestamp. If the file has been updated, it will be |
| 1037 |
reloaded and replace the current Log::Log4perl configuration. |
| 1038 |
|
| 1039 |
The way this works is that with every logger function called (debug(), |
| 1040 |
is_debug(), etc.), Log::Log4perl will check if the delay interval has |
| 1041 |
expired. If so, it will run a -M file check on the configuration file. |
| 1042 |
If its timestamp has been modified, the current configuration will be |
| 1043 |
dumped and new content of the file will be loaded. |
| 1044 |
|
| 1045 |
This convenience comes at a price, though: Calling time() with every |
| 1046 |
logging function call, especially the ones that are "suppressed" (!), |
| 1047 |
will slow down these Log4perl calls by about 40%. |
| 1048 |
|
| 1049 |
To alleviate this performance hit a bit, "init_and_watch()" can be |
| 1050 |
configured to listen for a Unix signal to reload the configuration |
| 1051 |
instead: |
| 1052 |
|
| 1053 |
Log::Log4perl->init_and_watch($conf_file, 'HUP'); |
| 1054 |
|
| 1055 |
This will set up a signal handler for SIGHUP and reload the |
| 1056 |
configuration if the application receives this signal, e.g. via the |
| 1057 |
"kill" command: |
| 1058 |
|
| 1059 |
kill -HUP pid |
| 1060 |
|
| 1061 |
where "pid" is the process ID of the application. This will bring you |
| 1062 |
back to about 85% of Log::Log4perl's normal execution speed for |
| 1063 |
suppressed statements. For details, check out "Performance". For more |
| 1064 |
info on the signal handler, look for "SIGNAL MODE" in |
| 1065 |
Log::Log4perl::Config::Watch. |
| 1066 |
|
| 1067 |
If you have a somewhat long delay set between physical config file |
| 1068 |
checks or don't want to use the signal associated with the config file |
| 1069 |
watcher, you can trigger a configuration reload at the next possible |
| 1070 |
time by calling "Log::Log4perl::Config->watcher->force_next_check()". |
| 1071 |
|
| 1072 |
One thing to watch out for: If the configuration file contains a syntax |
| 1073 |
or other fatal error, a running application will stop with "die" if this |
| 1074 |
damaged configuration will be loaded during runtime, triggered either by |
| 1075 |
a signal or if the delay period expired and the change is detected. This |
| 1076 |
behaviour might change in the future. |
| 1077 |
|
| 1078 |
To allow the application to intercept and control a configuration reload |
| 1079 |
in init_and_watch mode, a callback can be specified: |
| 1080 |
|
| 1081 |
Log::Log4perl->init_and_watch($conf_file, 10, { |
| 1082 |
preinit_callback => \&callback }); |
| 1083 |
|
| 1084 |
If Log4perl determines that the configuration needs to be reloaded, it |
| 1085 |
will call the "preinit_callback" function without parameters. If the |
| 1086 |
callback returns a true value, Log4perl will proceed and reload the |
| 1087 |
configuration. If the callback returns a false value, Log4perl will keep |
| 1088 |
the old configuration and skip reloading it until the next time around. |
| 1089 |
Inside the callback, an application can run all kinds of checks, |
| 1090 |
including accessing the configuration file, which is available via |
| 1091 |
"Log::Log4perl::Config->watcher()->file()". |
| 1092 |
|
| 1093 |
Variable Substitution |
| 1094 |
To avoid having to retype the same expressions over and over again, |
| 1095 |
Log::Log4perl's configuration files support simple variable |
| 1096 |
substitution. New variables are defined simply by adding |
| 1097 |
|
| 1098 |
varname = value |
| 1099 |
|
| 1100 |
lines to the configuration file before using |
| 1101 |
|
| 1102 |
${varname} |
| 1103 |
|
| 1104 |
afterwards to recall the assigned values. Here's an example: |
| 1105 |
|
| 1106 |
layout_class = Log::Log4perl::Layout::PatternLayout |
| 1107 |
layout_pattern = %d %F{1} %L> %m %n |
| 1108 |
|
| 1109 |
log4perl.category.Bar.Twix = WARN, Logfile, Screen |
| 1110 |
|
| 1111 |
log4perl.appender.Logfile = Log::Log4perl::Appender::File |
| 1112 |
log4perl.appender.Logfile.filename = test.log |
| 1113 |
log4perl.appender.Logfile.layout = ${layout_class} |
| 1114 |
log4perl.appender.Logfile.layout.ConversionPattern = ${layout_pattern} |
| 1115 |
|
| 1116 |
log4perl.appender.Screen = Log::Log4perl::Appender::Screen |
| 1117 |
log4perl.appender.Screen.layout = ${layout_class} |
| 1118 |
log4perl.appender.Screen.layout.ConversionPattern = ${layout_pattern} |
| 1119 |
|
| 1120 |
This is a convenient way to define two appenders with the same layout |
| 1121 |
without having to retype the pattern definitions. |
| 1122 |
|
| 1123 |
Variable substitution via "${varname}" will first try to find an |
| 1124 |
explicitly defined variable. If that fails, it will check your shell's |
| 1125 |
environment for a variable of that name. If that also fails, the program |
| 1126 |
will "die()". |
| 1127 |
|
| 1128 |
Perl Hooks in the Configuration File |
| 1129 |
If some of the values used in the Log4perl configuration file need to be |
| 1130 |
dynamically modified by the program, use Perl hooks: |
| 1131 |
|
| 1132 |
log4perl.appender.File.filename = \ |
| 1133 |
sub { return getLogfileName(); } |
| 1134 |
|
| 1135 |
Each value starting with the string "sub {..." is interpreted as Perl |
| 1136 |
code to be executed at the time the application parses the configuration |
| 1137 |
via "Log::Log4perl::init()". The return value of the subroutine is used |
| 1138 |
by Log::Log4perl as the configuration value. |
| 1139 |
|
| 1140 |
The Perl code is executed in the "main" package, functions in other |
| 1141 |
packages have to be called in fully-qualified notation. |
| 1142 |
|
| 1143 |
Here's another example, utilizing an environment variable as a username |
| 1144 |
for a DBI appender: |
| 1145 |
|
| 1146 |
log4perl.appender.DB.username = \ |
| 1147 |
sub { $ENV{DB_USER_NAME } } |
| 1148 |
|
| 1149 |
However, please note the difference between these code snippets and |
| 1150 |
those used for user-defined conversion specifiers as discussed in |
| 1151 |
Log::Log4perl::Layout::PatternLayout: While the snippets above are run |
| 1152 |
*once* when "Log::Log4perl::init()" is called, the conversion specifier |
| 1153 |
snippets are executed *each time* a message is rendered according to the |
| 1154 |
PatternLayout. |
| 1155 |
|
| 1156 |
SECURITY NOTE: this feature means arbitrary perl code can be embedded in |
| 1157 |
the config file. In the rare case where the people who have access to |
| 1158 |
your config file are different from the people who write your code and |
| 1159 |
shouldn't have execute rights, you might want to set |
| 1160 |
|
| 1161 |
Log::Log4perl::Config->allow_code(0); |
| 1162 |
|
| 1163 |
before you call init(). Alternatively you can supply a restricted set of |
| 1164 |
Perl opcodes that can be embedded in the config file as described in |
| 1165 |
"Restricting what Opcodes can be in a Perl Hook". |
| 1166 |
|
| 1167 |
Restricting what Opcodes can be in a Perl Hook |
| 1168 |
The value you pass to Log::Log4perl::Config->allow_code() determines |
| 1169 |
whether the code that is embedded in the config file is eval'd |
| 1170 |
unrestricted, or eval'd in a Safe compartment. By default, a value of |
| 1171 |
'1' is assumed, which does a normal 'eval' without any restrictions. A |
| 1172 |
value of '0' however prevents any embedded code from being evaluated. |
| 1173 |
|
| 1174 |
If you would like fine-grained control over what can and cannot be |
| 1175 |
included in embedded code, then please utilize the following methods: |
| 1176 |
|
| 1177 |
Log::Log4perl::Config->allow_code( $allow ); |
| 1178 |
Log::Log4perl::Config->allowed_code_ops($op1, $op2, ... ); |
| 1179 |
Log::Log4perl::Config->vars_shared_with_safe_compartment( [ \%vars | $package, \@vars ] ); |
| 1180 |
Log::Log4perl::Config->allowed_code_ops_convenience_map( [ \%map | $name, \@mask ] ); |
| 1181 |
|
| 1182 |
Log::Log4perl::Config->allowed_code_ops() takes a list of opcode masks |
| 1183 |
that are allowed to run in the compartment. The opcode masks must be |
| 1184 |
specified as described in Opcode: |
| 1185 |
|
| 1186 |
Log::Log4perl::Config->allowed_code_ops(':subprocess'); |
| 1187 |
|
| 1188 |
This example would allow Perl operations like backticks, system, fork, |
| 1189 |
and waitpid to be executed in the compartment. Of course, you probably |
| 1190 |
don't want to use this mask -- it would allow exactly what the Safe |
| 1191 |
compartment is designed to prevent. |
| 1192 |
|
| 1193 |
Log::Log4perl::Config->vars_shared_with_safe_compartment() takes the |
| 1194 |
symbols which should be exported into the Safe compartment before the |
| 1195 |
code is evaluated. The keys of this hash are the package names that the |
| 1196 |
symbols are in, and the values are array references to the literal |
| 1197 |
symbol names. For convenience, the default settings export the '%ENV' |
| 1198 |
hash from the 'main' package into the compartment: |
| 1199 |
|
| 1200 |
Log::Log4perl::Config->vars_shared_with_safe_compartment( |
| 1201 |
main => [ '%ENV' ], |
| 1202 |
); |
| 1203 |
|
| 1204 |
Log::Log4perl::Config->allowed_code_ops_convenience_map() is an accessor |
| 1205 |
method to a map of convenience names to opcode masks. At present, the |
| 1206 |
following convenience names are defined: |
| 1207 |
|
| 1208 |
safe = [ ':browse' ] |
| 1209 |
restrictive = [ ':default' ] |
| 1210 |
|
| 1211 |
For convenience, if Log::Log4perl::Config->allow_code() is called with a |
| 1212 |
value which is a key of the map previously defined with |
| 1213 |
Log::Log4perl::Config->allowed_code_ops_convenience_map(), then the |
| 1214 |
allowed opcodes are set according to the value defined in the map. If |
| 1215 |
this is confusing, consider the following: |
| 1216 |
|
| 1217 |
use Log::Log4perl; |
| 1218 |
|
| 1219 |
my $config = <<'END'; |
| 1220 |
log4perl.logger = INFO, Main |
| 1221 |
log4perl.appender.Main = Log::Log4perl::Appender::File |
| 1222 |
log4perl.appender.Main.filename = \ |
| 1223 |
sub { "example" . getpwuid($<) . ".log" } |
| 1224 |
log4perl.appender.Main.layout = Log::Log4perl::Layout::SimpleLayout |
| 1225 |
END |
| 1226 |
|
| 1227 |
$Log::Log4perl::Config->allow_code('restrictive'); |
| 1228 |
Log::Log4perl->init( \$config ); # will fail |
| 1229 |
$Log::Log4perl::Config->allow_code('safe'); |
| 1230 |
Log::Log4perl->init( \$config ); # will succeed |
| 1231 |
|
| 1232 |
The reason that the first call to ->init() fails is because the |
| 1233 |
'restrictive' name maps to an opcode mask of ':default'. getpwuid() is |
| 1234 |
not part of ':default', so ->init() fails. The 'safe' name maps to an |
| 1235 |
opcode mask of ':browse', which allows getpwuid() to run, so ->init() |
| 1236 |
succeeds. |
| 1237 |
|
| 1238 |
allowed_code_ops_convenience_map() can be invoked in several ways: |
| 1239 |
|
| 1240 |
allowed_code_ops_convenience_map() |
| 1241 |
Returns the entire convenience name map as a hash reference in |
| 1242 |
scalar context or a hash in list context. |
| 1243 |
|
| 1244 |
allowed_code_ops_convenience_map( \%map ) |
| 1245 |
Replaces the entire convenience name map with the supplied hash |
| 1246 |
reference. |
| 1247 |
|
| 1248 |
allowed_code_ops_convenience_map( $name ) |
| 1249 |
Returns the opcode mask for the given convenience name, or undef if |
| 1250 |
no such name is defined in the map. |
| 1251 |
|
| 1252 |
allowed_code_ops_convenience_map( $name, \@mask ) |
| 1253 |
Adds the given name/mask pair to the convenience name map. If the |
| 1254 |
name already exists in the map, it's value is replaced with the new |
| 1255 |
mask. |
| 1256 |
|
| 1257 |
as can vars_shared_with_safe_compartment(): |
| 1258 |
|
| 1259 |
vars_shared_with_safe_compartment() |
| 1260 |
Return the entire map of packages to variables as a hash reference |
| 1261 |
in scalar context or a hash in list context. |
| 1262 |
|
| 1263 |
vars_shared_with_safe_compartment( \%packages ) |
| 1264 |
Replaces the entire map of packages to variables with the supplied |
| 1265 |
hash reference. |
| 1266 |
|
| 1267 |
vars_shared_with_safe_compartment( $package ) |
| 1268 |
Returns the arrayref of variables to be shared for a specific |
| 1269 |
package. |
| 1270 |
|
| 1271 |
vars_shared_with_safe_compartment( $package, \@vars ) |
| 1272 |
Adds the given package / varlist pair to the map. If the package |
| 1273 |
already exists in the map, it's value is replaced with the new |
| 1274 |
arrayref of variable names. |
| 1275 |
|
| 1276 |
For more information on opcodes and Safe Compartments, see Opcode and |
| 1277 |
Safe. |
| 1278 |
|
| 1279 |
Changing the Log Level on a Logger |
| 1280 |
Log4perl provides some internal functions for quickly adjusting the log |
| 1281 |
level from within a running Perl program. |
| 1282 |
|
| 1283 |
Now, some people might argue that you should adjust your levels from |
| 1284 |
within an external Log4perl configuration file, but Log4perl is |
| 1285 |
everybody's darling. |
| 1286 |
|
| 1287 |
Typically run-time adjusting of levels is done at the beginning, or in |
| 1288 |
response to some external input (like a "more logging" runtime command |
| 1289 |
for diagnostics). |
| 1290 |
|
| 1291 |
You get the log level from a logger object with: |
| 1292 |
|
| 1293 |
$current_level = $logger->level(); |
| 1294 |
|
| 1295 |
and you may set it with the same method, provided you first imported the |
| 1296 |
log level constants, with: |
| 1297 |
|
| 1298 |
use Log::Log4perl::Level; |
| 1299 |
|
| 1300 |
Then you can set the level on a logger to one of the constants, |
| 1301 |
|
| 1302 |
$logger->level($ERROR); # one of DEBUG, INFO, WARN, ERROR, FATAL |
| 1303 |
|
| 1304 |
To increase the level of logging currently being done, use: |
| 1305 |
|
| 1306 |
$logger->more_logging($delta); |
| 1307 |
|
| 1308 |
and to decrease it, use: |
| 1309 |
|
| 1310 |
$logger->less_logging($delta); |
| 1311 |
|
| 1312 |
$delta must be a positive integer (for now, we may fix this later ;). |
| 1313 |
|
| 1314 |
There are also two equivalent functions: |
| 1315 |
|
| 1316 |
$logger->inc_level($delta); |
| 1317 |
$logger->dec_level($delta); |
| 1318 |
|
| 1319 |
They're included to allow you a choice in readability. Some folks will |
| 1320 |
prefer more/less_logging, as they're fairly clear in what they do, and |
| 1321 |
allow the programmer not to worry too much about what a Level is and |
| 1322 |
whether a higher level means more or less logging. However, other folks |
| 1323 |
who do understand and have lots of code that deals with levels will |
| 1324 |
probably prefer the inc_level() and dec_level() methods as they want to |
| 1325 |
work with Levels and not worry about whether that means more or less |
| 1326 |
logging. :) |
| 1327 |
|
| 1328 |
That diatribe aside, typically you'll use more_logging() or inc_level() |
| 1329 |
as such: |
| 1330 |
|
| 1331 |
my $v = 0; # default level of verbosity. |
| 1332 |
|
| 1333 |
GetOptions("v+" => \$v, ...); |
| 1334 |
|
| 1335 |
if( $v ) { |
| 1336 |
$logger->more_logging($v); # inc logging level once for each -v in ARGV |
| 1337 |
} |
| 1338 |
|
| 1339 |
Custom Log Levels |
| 1340 |
First off, let me tell you that creating custom levels is heavily |
| 1341 |
deprecated by the log4j folks. Indeed, instead of creating additional |
| 1342 |
levels on top of the predefined DEBUG, INFO, WARN, ERROR and FATAL, you |
| 1343 |
should use categories to control the amount of logging smartly, based on |
| 1344 |
the location of the log-active code in the system. |
| 1345 |
|
| 1346 |
Nevertheless, Log4perl provides a nice way to create custom levels via |
| 1347 |
the create_custom_level() routine function. However, this must be done |
| 1348 |
before the first call to init() or get_logger(). Say you want to create |
| 1349 |
a NOTIFY logging level that comes after WARN (and thus before INFO). |
| 1350 |
You'd do such as follows: |
| 1351 |
|
| 1352 |
use Log::Log4perl; |
| 1353 |
use Log::Log4perl::Level; |
| 1354 |
|
| 1355 |
Log::Log4perl::Logger::create_custom_level("NOTIFY", "WARN"); |
| 1356 |
|
| 1357 |
And that's it! "create_custom_level()" creates the following functions / |
| 1358 |
variables for level FOO: |
| 1359 |
|
| 1360 |
$FOO_INT # integer to use in L4p::Level::to_level() |
| 1361 |
$logger->foo() # log function to log if level = FOO |
| 1362 |
$logger->is_foo() # true if current level is >= FOO |
| 1363 |
|
| 1364 |
These levels can also be used in your config file, but note that your |
| 1365 |
config file probably won't be portable to another log4perl or log4j |
| 1366 |
environment unless you've made the appropriate mods there too. |
| 1367 |
|
| 1368 |
Since Log4perl translates log levels to syslog and Log::Dispatch if |
| 1369 |
their appenders are used, you may add mappings for custom levels as |
| 1370 |
well: |
| 1371 |
|
| 1372 |
Log::Log4perl::Level::add_priority("NOTIFY", "WARN", |
| 1373 |
$syslog_equiv, $log_dispatch_level); |
| 1374 |
|
| 1375 |
For example, if your new custom "NOTIFY" level is supposed to map to |
| 1376 |
syslog level 2 ("LOG_NOTICE") and Log::Dispatch level 2 ("notice"), use: |
| 1377 |
|
| 1378 |
Log::Log4perl::Logger::create_custom_level("NOTIFY", "WARN", 2, 2); |
| 1379 |
|
| 1380 |
System-wide log levels |
| 1381 |
As a fairly drastic measure to decrease (or increase) the logging level |
| 1382 |
all over the system with one single configuration option, use the |
| 1383 |
"threshold" keyword in the Log4perl configuration file: |
| 1384 |
|
| 1385 |
log4perl.threshold = ERROR |
| 1386 |
|
| 1387 |
sets the system-wide (or hierarchy-wide according to the log4j |
| 1388 |
documentation) to ERROR and therefore deprives every logger in the |
| 1389 |
system of the right to log lower-prio messages. |
| 1390 |
|
| 1391 |
Easy Mode |
| 1392 |
For teaching purposes (especially for [1]), I've put ":easy" mode into |
| 1393 |
"Log::Log4perl", which just initializes a single root logger with a |
| 1394 |
defined priority and a screen appender including some nice standard |
| 1395 |
layout: |
| 1396 |
|
| 1397 |
### Initialization Section |
| 1398 |
use Log::Log4perl qw(:easy); |
| 1399 |
Log::Log4perl->easy_init($ERROR); # Set priority of root logger to ERROR |
| 1400 |
|
| 1401 |
### Application Section |
| 1402 |
my $logger = get_logger(); |
| 1403 |
$logger->fatal("This will get logged."); |
| 1404 |
$logger->debug("This won't."); |
| 1405 |
|
| 1406 |
This will dump something like |
| 1407 |
|
| 1408 |
2002/08/04 11:43:09 ERROR> script.pl:16 main::function - This will get logged. |
| 1409 |
|
| 1410 |
to the screen. While this has been proven to work well familiarizing |
| 1411 |
people with "Log::Logperl" slowly, effectively avoiding to clobber them |
| 1412 |
over the head with a plethora of different knobs to fiddle with |
| 1413 |
(categories, appenders, levels, layout), the overall mission of |
| 1414 |
"Log::Log4perl" is to let people use categories right from the start to |
| 1415 |
get used to the concept. So, let's keep this one fairly hidden in the |
| 1416 |
man page (congrats on reading this far :). |
| 1417 |
|
| 1418 |
Stealth loggers |
| 1419 |
Sometimes, people are lazy. If you're whipping up a 50-line script and |
| 1420 |
want the comfort of Log::Log4perl without having the burden of carrying |
| 1421 |
a separate log4perl.conf file or a 5-liner defining that you want to |
| 1422 |
append your log statements to a file, you can use the following |
| 1423 |
features: |
| 1424 |
|
| 1425 |
use Log::Log4perl qw(:easy); |
| 1426 |
|
| 1427 |
Log::Log4perl->easy_init( { level => $DEBUG, |
| 1428 |
file => ">>test.log" } ); |
| 1429 |
|
| 1430 |
# Logs to test.log via stealth logger |
| 1431 |
DEBUG("Debug this!"); |
| 1432 |
INFO("Info this!"); |
| 1433 |
WARN("Warn this!"); |
| 1434 |
ERROR("Error this!"); |
| 1435 |
|
| 1436 |
some_function(); |
| 1437 |
|
| 1438 |
sub some_function { |
| 1439 |
# Same here |
| 1440 |
FATAL("Fatal this!"); |
| 1441 |
} |
| 1442 |
|
| 1443 |
In ":easy" mode, "Log::Log4perl" will instantiate a *stealth logger* and |
| 1444 |
introduce the convenience functions "TRACE", "DEBUG()", "INFO()", |
| 1445 |
"WARN()", "ERROR()", "FATAL()", and "ALWAYS" into the package namespace. |
| 1446 |
These functions simply take messages as arguments and forward them to |
| 1447 |
the stealth loggers methods ("debug()", "info()", and so on). |
| 1448 |
|
| 1449 |
If a message should never be blocked, regardless of the log level, use |
| 1450 |
the "ALWAYS" function which corresponds to a log level of "OFF": |
| 1451 |
|
| 1452 |
ALWAYS "This will be printed regardless of the log level"; |
| 1453 |
|
| 1454 |
The "easy_init" method can be called with a single level value to create |
| 1455 |
a STDERR appender and a root logger as in |
| 1456 |
|
| 1457 |
Log::Log4perl->easy_init($DEBUG); |
| 1458 |
|
| 1459 |
or, as shown below (and in the example above) with a reference to a |
| 1460 |
hash, specifying values for "level" (the logger's priority), "file" (the |
| 1461 |
appender's data sink), "category" (the logger's category and "layout" |
| 1462 |
for the appender's pattern layout specification. All key-value pairs are |
| 1463 |
optional, they default to $DEBUG for "level", "STDERR" for "file", "" |
| 1464 |
(root category) for "category" and "%d %m%n" for "layout": |
| 1465 |
|
| 1466 |
Log::Log4perl->easy_init( { level => $DEBUG, |
| 1467 |
file => ">test.log", |
| 1468 |
utf8 => 1, |
| 1469 |
category => "Bar::Twix", |
| 1470 |
layout => '%F{1}-%L-%M: %m%n' } ); |
| 1471 |
|
| 1472 |
The "file" parameter takes file names preceded by ">" (overwrite) and |
| 1473 |
">>" (append) as arguments. This will cause |
| 1474 |
"Log::Log4perl::Appender::File" appenders to be created behind the |
| 1475 |
scenes. Also the keywords "STDOUT" and "STDERR" (no ">" or ">>") are |
| 1476 |
recognized, which will utilize and configure |
| 1477 |
"Log::Log4perl::Appender::Screen" appropriately. The "utf8" flag, if set |
| 1478 |
to a true value, runs a "binmode" command on the file handle to |
| 1479 |
establish a utf8 line discipline on the file, otherwise you'll get a |
| 1480 |
'wide character in print' warning message and probably not what you'd |
| 1481 |
expect as output. |
| 1482 |
|
| 1483 |
The stealth loggers can be used in different packages, you just need to |
| 1484 |
make sure you're calling the "use" function in every package you're |
| 1485 |
using "Log::Log4perl"'s easy services: |
| 1486 |
|
| 1487 |
package Bar::Twix; |
| 1488 |
use Log::Log4perl qw(:easy); |
| 1489 |
sub eat { DEBUG("Twix mjam"); } |
| 1490 |
|
| 1491 |
package Bar::Mars; |
| 1492 |
use Log::Log4perl qw(:easy); |
| 1493 |
sub eat { INFO("Mars mjam"); } |
| 1494 |
|
| 1495 |
package main; |
| 1496 |
|
| 1497 |
use Log::Log4perl qw(:easy); |
| 1498 |
|
| 1499 |
Log::Log4perl->easy_init( { level => $DEBUG, |
| 1500 |
file => ">>test.log", |
| 1501 |
category => "Bar::Twix", |
| 1502 |
layout => '%F{1}-%L-%M: %m%n' }, |
| 1503 |
{ level => $DEBUG, |
| 1504 |
file => "STDOUT", |
| 1505 |
category => "Bar::Mars", |
| 1506 |
layout => '%m%n' }, |
| 1507 |
); |
| 1508 |
Bar::Twix::eat(); |
| 1509 |
Bar::Mars::eat(); |
| 1510 |
|
| 1511 |
As shown above, "easy_init()" will take any number of different logger |
| 1512 |
definitions as hash references. |
| 1513 |
|
| 1514 |
Also, stealth loggers feature the functions "LOGWARN()", "LOGDIE()", and |
| 1515 |
"LOGEXIT()", combining a logging request with a subsequent Perl warn() |
| 1516 |
or die() or exit() statement. So, for example |
| 1517 |
|
| 1518 |
if($all_is_lost) { |
| 1519 |
LOGDIE("Terrible Problem"); |
| 1520 |
} |
| 1521 |
|
| 1522 |
will log the message if the package's logger is at least "FATAL" but |
| 1523 |
"die()" (including the traditional output to STDERR) in any case |
| 1524 |
afterwards. |
| 1525 |
|
| 1526 |
See "Log and die or warn" for the similar "logdie()" and "logwarn()" |
| 1527 |
functions of regular (i.e non-stealth) loggers. |
| 1528 |
|
| 1529 |
Similarily, "LOGCARP()", "LOGCLUCK()", "LOGCROAK()", and "LOGCONFESS()" |
| 1530 |
are provided in ":easy" mode, facilitating the use of "logcarp()", |
| 1531 |
"logcluck()", "logcroak()", and "logconfess()" with stealth loggers. |
| 1532 |
|
| 1533 |
When using Log::Log4perl in easy mode, please make sure you understand |
| 1534 |
the implications of "Pitfalls with Categories". |
| 1535 |
|
| 1536 |
By the way, these convenience functions perform exactly as fast as the |
| 1537 |
standard Log::Log4perl logger methods, there's *no* performance penalty |
| 1538 |
whatsoever. |
| 1539 |
|
| 1540 |
Nested Diagnostic Context (NDC) |
| 1541 |
If you find that your application could use a global (thread-specific) |
| 1542 |
data stack which your loggers throughout the system have easy access to, |
| 1543 |
use Nested Diagnostic Contexts (NDCs). Also check out "Mapped Diagnostic |
| 1544 |
Context (MDC)", this might turn out to be even more useful. |
| 1545 |
|
| 1546 |
For example, when handling a request of a web client, it's probably |
| 1547 |
useful to have the user's IP address available in all log statements |
| 1548 |
within code dealing with this particular request. Instead of passing |
| 1549 |
this piece of data around between your application functions, you can |
| 1550 |
just use the global (but thread-specific) NDC mechanism. It allows you |
| 1551 |
to push data pieces (scalars usually) onto its stack via |
| 1552 |
|
| 1553 |
Log::Log4perl::NDC->push("San"); |
| 1554 |
Log::Log4perl::NDC->push("Francisco"); |
| 1555 |
|
| 1556 |
and have your loggers retrieve them again via the "%x" placeholder in |
| 1557 |
the PatternLayout. With the stack values above and a PatternLayout |
| 1558 |
format like "%x %m%n", the call |
| 1559 |
|
| 1560 |
$logger->debug("rocks"); |
| 1561 |
|
| 1562 |
will end up as |
| 1563 |
|
| 1564 |
San Francisco rocks |
| 1565 |
|
| 1566 |
in the log appender. |
| 1567 |
|
| 1568 |
The stack mechanism allows for nested structures. Just make sure that at |
| 1569 |
the end of the request, you either decrease the stack one by one by |
| 1570 |
calling |
| 1571 |
|
| 1572 |
Log::Log4perl::NDC->pop(); |
| 1573 |
Log::Log4perl::NDC->pop(); |
| 1574 |
|
| 1575 |
or clear out the entire NDC stack by calling |
| 1576 |
|
| 1577 |
Log::Log4perl::NDC->remove(); |
| 1578 |
|
| 1579 |
Even if you should forget to do that, "Log::Log4perl" won't grow the |
| 1580 |
stack indefinitely, but limit it to a maximum, defined in |
| 1581 |
"Log::Log4perl::NDC" (currently 5). A call to "push()" on a full stack |
| 1582 |
will just replace the topmost element by the new value. |
| 1583 |
|
| 1584 |
Again, the stack is always available via the "%x" placeholder in the |
| 1585 |
Log::Log4perl::Layout::PatternLayout class whenever a logger fires. It |
| 1586 |
will replace "%x" by the blank-separated list of the values on the |
| 1587 |
stack. It does that by just calling |
| 1588 |
|
| 1589 |
Log::Log4perl::NDC->get(); |
| 1590 |
|
| 1591 |
internally. See details on how this standard log4j feature is |
| 1592 |
implemented in Log::Log4perl::NDC. |
| 1593 |
|
| 1594 |
Mapped Diagnostic Context (MDC) |
| 1595 |
Just like the previously discussed NDC stores thread-specific |
| 1596 |
information in a stack structure, the MDC implements a hash table to |
| 1597 |
store key/value pairs in. |
| 1598 |
|
| 1599 |
The static method |
| 1600 |
|
| 1601 |
Log::Log4perl::MDC->put($key, $value); |
| 1602 |
|
| 1603 |
stores $value under a key $key, with which it can be retrieved later |
| 1604 |
(possibly in a totally different part of the system) by calling the |
| 1605 |
"get" method: |
| 1606 |
|
| 1607 |
my $value = Log::Log4perl::MDC->get($key); |
| 1608 |
|
| 1609 |
If no value has been stored previously under $key, the "get" method will |
| 1610 |
return "undef". |
| 1611 |
|
| 1612 |
Typically, MDC values are retrieved later on via the "%X{...}" |
| 1613 |
placeholder in "Log::Log4perl::Layout::PatternLayout". If the "get()" |
| 1614 |
method returns "undef", the placeholder will expand to the string |
| 1615 |
"[undef]". |
| 1616 |
|
| 1617 |
An application taking a web request might store the remote host like |
| 1618 |
|
| 1619 |
Log::Log4perl::MDC->put("remote_host", $r->headers("HOST")); |
| 1620 |
|
| 1621 |
at its beginning and if the appender's layout looks something like |
| 1622 |
|
| 1623 |
log4perl.appender.Logfile.layout.ConversionPattern = %X{remote_host}: %m%n |
| 1624 |
|
| 1625 |
then a log statement like |
| 1626 |
|
| 1627 |
DEBUG("Content delivered"); |
| 1628 |
|
| 1629 |
will log something like |
| 1630 |
|
| 1631 |
adsl-63.dsl.snf.pacbell.net: Content delivered |
| 1632 |
|
| 1633 |
later on in the program. |
| 1634 |
|
| 1635 |
For details, please check Log::Log4perl::MDC. |
| 1636 |
|
| 1637 |
Resurrecting hidden Log4perl Statements |
| 1638 |
Sometimes scripts need to be deployed in environments without having |
| 1639 |
Log::Log4perl installed yet. On the other hand, you don't want to live |
| 1640 |
without your Log4perl statements -- they're gonna come in handy later. |
| 1641 |
|
| 1642 |
So, just deploy your script with Log4perl statements commented out with |
| 1643 |
the pattern "###l4p", like in |
| 1644 |
|
| 1645 |
###l4p DEBUG "It works!"; |
| 1646 |
# ... |
| 1647 |
###l4p INFO "Really!"; |
| 1648 |
|
| 1649 |
If Log::Log4perl is available, use the ":resurrect" tag to have Log4perl |
| 1650 |
resurrect those buried statements before the script starts running: |
| 1651 |
|
| 1652 |
use Log::Log4perl qw(:resurrect :easy); |
| 1653 |
|
| 1654 |
###l4p Log::Log4perl->easy_init($DEBUG); |
| 1655 |
###l4p DEBUG "It works!"; |
| 1656 |
# ... |
| 1657 |
###l4p INFO "Really!"; |
| 1658 |
|
| 1659 |
This will have a source filter kick in and indeed print |
| 1660 |
|
| 1661 |
2004/11/18 22:08:46 It works! |
| 1662 |
2004/11/18 22:08:46 Really! |
| 1663 |
|
| 1664 |
In environments lacking Log::Log4perl, just comment out the first line |
| 1665 |
and the script will run nevertheless (but of course without logging): |
| 1666 |
|
| 1667 |
# use Log::Log4perl qw(:resurrect :easy); |
| 1668 |
|
| 1669 |
###l4p Log::Log4perl->easy_init($DEBUG); |
| 1670 |
###l4p DEBUG "It works!"; |
| 1671 |
# ... |
| 1672 |
###l4p INFO "Really!"; |
| 1673 |
|
| 1674 |
because everything's a regular comment now. Alternatively, put the magic |
| 1675 |
Log::Log4perl comment resurrection line into your shell's PERL5OPT |
| 1676 |
environment variable, e.g. for bash: |
| 1677 |
|
| 1678 |
set PERL5OPT=-MLog::Log4perl=:resurrect,:easy |
| 1679 |
export PERL5OPT |
| 1680 |
|
| 1681 |
This will awaken the giant within an otherwise silent script like the |
| 1682 |
following: |
| 1683 |
|
| 1684 |
#!/usr/bin/perl |
| 1685 |
|
| 1686 |
###l4p Log::Log4perl->easy_init($DEBUG); |
| 1687 |
###l4p DEBUG "It works!"; |
| 1688 |
|
| 1689 |
As of "Log::Log4perl" 1.12, you can even force *all* modules loaded by a |
| 1690 |
script to have their hidden Log4perl statements resurrected. For this to |
| 1691 |
happen, load "Log::Log4perl::Resurrector" *before* loading any modules: |
| 1692 |
|
| 1693 |
use Log::Log4perl qw(:easy); |
| 1694 |
use Log::Log4perl::Resurrector; |
| 1695 |
|
| 1696 |
use Foobar; # All hidden Log4perl statements in here will |
| 1697 |
# be uncommented before Foobar gets loaded. |
| 1698 |
|
| 1699 |
Log::Log4perl->easy_init($DEBUG); |
| 1700 |
... |
| 1701 |
|
| 1702 |
Check the "Log::Log4perl::Resurrector" manpage for more details. |
| 1703 |
|
| 1704 |
Access defined appenders |
| 1705 |
All appenders defined in the configuration file or via Perl code can be |
| 1706 |
retrieved by the "appender_by_name()" class method. This comes in handy |
| 1707 |
if you want to manipulate or query appender properties after the |
| 1708 |
Log4perl configuration has been loaded via "init()". |
| 1709 |
|
| 1710 |
Note that internally, Log::Log4perl uses the "Log::Log4perl::Appender" |
| 1711 |
wrapper class to control the real appenders (like |
| 1712 |
"Log::Log4perl::Appender::File" or "Log::Dispatch::FileRotate"). The |
| 1713 |
"Log::Log4perl::Appender" class has an "appender" attribute, pointing to |
| 1714 |
the real appender. |
| 1715 |
|
| 1716 |
The reason for this is that external appenders like |
| 1717 |
"Log::Dispatch::FileRotate" don't support all of Log::Log4perl's |
| 1718 |
appender control mechanisms (like appender thresholds). |
| 1719 |
|
| 1720 |
The previously mentioned method "appender_by_name()" returns a reference |
| 1721 |
to the *real* appender object. If you want access to the wrapper class |
| 1722 |
(e.g. if you want to modify the appender's threshold), use the hash |
| 1723 |
$Log::Log4perl::Logger::APPENDER_BY_NAME{...} instead, which holds |
| 1724 |
references to all appender wrapper objects. |
| 1725 |
|
| 1726 |
Modify appender thresholds |
| 1727 |
To set an appender's threshold, use its "threshold()" method: |
| 1728 |
|
| 1729 |
$app->threshold( $FATAL ); |
| 1730 |
|
| 1731 |
To conveniently adjust *all* appender thresholds (e.g. because a script |
| 1732 |
uses more_logging()), use |
| 1733 |
|
| 1734 |
# decrease thresholds of all appenders |
| 1735 |
Log::Log4perl->appender_thresholds_adjust(-1); |
| 1736 |
|
| 1737 |
This will decrease the thresholds of all appenders in the system by one |
| 1738 |
level, i.e. WARN becomes INFO, INFO becomes DEBUG, etc. To only modify |
| 1739 |
selected ones, use |
| 1740 |
|
| 1741 |
# decrease thresholds of selected appenders |
| 1742 |
Log::Log4perl->appender_thresholds_adjust(-1, ['AppName1', ...]); |
| 1743 |
|
| 1744 |
and pass the names of affected appenders in a ref to an array. |
| 1745 |
|
| 1746 |
Advanced configuration within Perl |
| 1747 |
Initializing Log::Log4perl can certainly also be done from within Perl. |
| 1748 |
At last, this is what "Log::Log4perl::Config" does behind the scenes. |
| 1749 |
Log::Log4perl's configuration file parsers are using a publically |
| 1750 |
available API to set up Log::Log4perl's categories, appenders and |
| 1751 |
layouts. |
| 1752 |
|
| 1753 |
Here's an example on how to configure two appenders with the same layout |
| 1754 |
in Perl, without using a configuration file at all: |
| 1755 |
|
| 1756 |
######################## |
| 1757 |
# Initialization section |
| 1758 |
######################## |
| 1759 |
use Log::Log4perl; |
| 1760 |
use Log::Log4perl::Layout; |
| 1761 |
use Log::Log4perl::Level; |
| 1762 |
|
| 1763 |
# Define a category logger |
| 1764 |
my $log = Log::Log4perl->get_logger("Foo::Bar"); |
| 1765 |
|
| 1766 |
# Define a layout |
| 1767 |
my $layout = Log::Log4perl::Layout::PatternLayout->new("[%r] %F %L %m%n"); |
| 1768 |
|
| 1769 |
# Define a file appender |
| 1770 |
my $file_appender = Log::Log4perl::Appender->new( |
| 1771 |
"Log::Log4perl::Appender::File", |
| 1772 |
name => "filelog", |
| 1773 |
filename => "/tmp/my.log"); |
| 1774 |
|
| 1775 |
# Define a stdout appender |
| 1776 |
my $stdout_appender = Log::Log4perl::Appender->new( |
| 1777 |
"Log::Log4perl::Appender::Screen", |
| 1778 |
name => "screenlog", |
| 1779 |
stderr => 0); |
| 1780 |
|
| 1781 |
# Have both appenders use the same layout (could be different) |
| 1782 |
$stdout_appender->layout($layout); |
| 1783 |
$file_appender->layout($layout); |
| 1784 |
|
| 1785 |
$log->add_appender($stdout_appender); |
| 1786 |
$log->add_appender($file_appender); |
| 1787 |
$log->level($INFO); |
| 1788 |
|
| 1789 |
Please note the class of the appender object is passed as a *string* to |
| 1790 |
"Log::Log4perl::Appender" in the *first* argument. Behind the scenes, |
| 1791 |
"Log::Log4perl::Appender" will create the necessary |
| 1792 |
"Log::Log4perl::Appender::*" (or "Log::Dispatch::*") object and pass |
| 1793 |
along the name value pairs we provided to |
| 1794 |
"Log::Log4perl::Appender->new()" after the first argument. |
| 1795 |
|
| 1796 |
The "name" value is optional and if you don't provide one, |
| 1797 |
"Log::Log4perl::Appender->new()" will create a unique one for you. The |
| 1798 |
names and values of additional parameters are dependent on the |
| 1799 |
requirements of the particular appender class and can be looked up in |
| 1800 |
their manual pages. |
| 1801 |
|
| 1802 |
A side note: In case you're wondering if |
| 1803 |
"Log::Log4perl::Appender->new()" will also take care of the "min_level" |
| 1804 |
argument to the "Log::Dispatch::*" constructors called behind the scenes |
| 1805 |
-- yes, it does. This is because we want the "Log::Dispatch" objects to |
| 1806 |
blindly log everything we send them ("debug" is their lowest setting) |
| 1807 |
because *we* in "Log::Log4perl" want to call the shots and decide on |
| 1808 |
when and what to log. |
| 1809 |
|
| 1810 |
The call to the appender's *layout()* method specifies the format (as a |
| 1811 |
previously created "Log::Log4perl::Layout::PatternLayout" object) in |
| 1812 |
which the message is being logged in the specified appender. If you |
| 1813 |
don't specify a layout, the logger will fall back to |
| 1814 |
"Log::Log4perl::SimpleLayout", which logs the debug level, a hyphen (-) |
| 1815 |
and the log message. |
| 1816 |
|
| 1817 |
Layouts are objects, here's how you create them: |
| 1818 |
|
| 1819 |
# Create a simple layout |
| 1820 |
my $simple = Log::Log4perl::SimpleLayout(); |
| 1821 |
|
| 1822 |
# create a flexible layout: |
| 1823 |
# ("yyyy/MM/dd HH:mm:ss (file:lineno)> message\n") |
| 1824 |
my $pattern = Log::Log4perl::Layout::PatternLayout("%d (%F:%L)> %m%n"); |
| 1825 |
|
| 1826 |
Every appender has exactly one layout assigned to it. You assign the |
| 1827 |
layout to the appender using the appender's "layout()" object: |
| 1828 |
|
| 1829 |
my $app = Log::Log4perl::Appender->new( |
| 1830 |
"Log::Log4perl::Appender::Screen", |
| 1831 |
name => "screenlog", |
| 1832 |
stderr => 0); |
| 1833 |
|
| 1834 |
# Assign the previously defined flexible layout |
| 1835 |
$app->layout($pattern); |
| 1836 |
|
| 1837 |
# Add the appender to a previously defined logger |
| 1838 |
$logger->add_appender($app); |
| 1839 |
|
| 1840 |
# ... and you're good to go! |
| 1841 |
$logger->debug("Blah"); |
| 1842 |
# => "2002/07/10 23:55:35 (test.pl:207)> Blah\n" |
| 1843 |
|
| 1844 |
It's also possible to remove appenders from a logger: |
| 1845 |
|
| 1846 |
$logger->remove_appender($appender_name); |
| 1847 |
|
| 1848 |
will remove an appender, specified by name, from a given logger. Please |
| 1849 |
note that this does *not* remove an appender from the system. |
| 1850 |
|
| 1851 |
To eradicate an appender from the system, you need to call |
| 1852 |
"Log::Log4perl->eradicate_appender($appender_name)" which will first |
| 1853 |
remove the appender from every logger in the system and then will delete |
| 1854 |
all references Log4perl holds to it. |
| 1855 |
|
| 1856 |
To remove a logger from the system, use |
| 1857 |
"Log::Log4perl->remove_logger($logger)". After the remaining reference |
| 1858 |
$logger goes away, the logger will self-destruct. If the logger in |
| 1859 |
question is a stealth logger, all of its convenience shortcuts (DEBUG, |
| 1860 |
INFO, etc) will turn into no-ops. |
| 1861 |
|
| 1862 |
How about Log::Dispatch::Config? |
| 1863 |
Tatsuhiko Miyagawa's "Log::Dispatch::Config" is a very clever simplified |
| 1864 |
logger implementation, covering some of the *log4j* functionality. Among |
| 1865 |
the things that "Log::Log4perl" can but "Log::Dispatch::Config" can't |
| 1866 |
are: |
| 1867 |
|
| 1868 |
* You can't assign categories to loggers. For small systems that's |
| 1869 |
fine, but if you can't turn off and on detailed logging in only a |
| 1870 |
tiny subsystem of your environment, you're missing out on a majorly |
| 1871 |
useful log4j feature. |
| 1872 |
|
| 1873 |
* Defining appender thresholds. Important if you want to solve |
| 1874 |
problems like "log all messages of level FATAL to STDERR, plus log |
| 1875 |
all DEBUG messages in "Foo::Bar" to a log file". If you don't have |
| 1876 |
appenders thresholds, there's no way to prevent cluttering STDERR |
| 1877 |
with DEBUG messages. |
| 1878 |
|
| 1879 |
* PatternLayout specifications in accordance with the standard (e.g. |
| 1880 |
"%d{HH:mm}"). |
| 1881 |
|
| 1882 |
Bottom line: Log::Dispatch::Config is fine for small systems with simple |
| 1883 |
logging requirements. However, if you're designing a system with lots of |
| 1884 |
subsystems which you need to control independently, you'll love the |
| 1885 |
features of "Log::Log4perl", which is equally easy to use. |
| 1886 |
|
| 1887 |
Using Log::Log4perl with wrapper functions and classes |
| 1888 |
If you don't use "Log::Log4perl" as described above, but from a wrapper |
| 1889 |
function, the pattern layout will generate wrong data for %F, %C, %L, |
| 1890 |
and the like. Reason for this is that "Log::Log4perl"'s loggers assume a |
| 1891 |
static caller depth to the application that's using them. |
| 1892 |
|
| 1893 |
If you're using one (or more) wrapper functions, "Log::Log4perl" will |
| 1894 |
indicate where your logger function called the loggers, not where your |
| 1895 |
application called your wrapper: |
| 1896 |
|
| 1897 |
use Log::Log4perl qw(:easy); |
| 1898 |
Log::Log4perl->easy_init({ level => $DEBUG, |
| 1899 |
layout => "%M %m%n" }); |
| 1900 |
|
| 1901 |
sub mylog { |
| 1902 |
my($message) = @_; |
| 1903 |
|
| 1904 |
DEBUG $message; |
| 1905 |
} |
| 1906 |
|
| 1907 |
sub func { |
| 1908 |
mylog "Hello"; |
| 1909 |
} |
| 1910 |
|
| 1911 |
func(); |
| 1912 |
|
| 1913 |
prints |
| 1914 |
|
| 1915 |
main::mylog Hello |
| 1916 |
|
| 1917 |
but that's probably not what your application expects. Rather, you'd |
| 1918 |
want |
| 1919 |
|
| 1920 |
main::func Hello |
| 1921 |
|
| 1922 |
because the "func" function called your logging function. |
| 1923 |
|
| 1924 |
But don't despair, there's a solution: Just register your wrapper |
| 1925 |
package with Log4perl beforehand. If Log4perl then finds that it's being |
| 1926 |
called from a registered wrapper, it will automatically step up to the |
| 1927 |
next call frame. |
| 1928 |
|
| 1929 |
Log::Log4perl->wrapper_register(__PACKAGE__); |
| 1930 |
|
| 1931 |
sub mylog { |
| 1932 |
my($message) = @_; |
| 1933 |
|
| 1934 |
DEBUG $message; |
| 1935 |
} |
| 1936 |
|
| 1937 |
Alternatively, you can increase the value of the global variable |
| 1938 |
$Log::Log4perl::caller_depth (defaults to 0) by one for every wrapper |
| 1939 |
that's in between your application and "Log::Log4perl", then |
| 1940 |
"Log::Log4perl" will compensate for the difference: |
| 1941 |
|
| 1942 |
sub mylog { |
| 1943 |
my($message) = @_; |
| 1944 |
|
| 1945 |
local $Log::Log4perl::caller_depth = |
| 1946 |
$Log::Log4perl::caller_depth + 1; |
| 1947 |
DEBUG $message; |
| 1948 |
} |
| 1949 |
|
| 1950 |
Also, note that if you're writing a subclass of Log4perl, like |
| 1951 |
|
| 1952 |
package MyL4pWrapper; |
| 1953 |
use Log::Log4perl; |
| 1954 |
our @ISA = qw(Log::Log4perl); |
| 1955 |
|
| 1956 |
and you want to call get_logger() in your code, like |
| 1957 |
|
| 1958 |
use MyL4pWrapper; |
| 1959 |
|
| 1960 |
sub get_logger { |
| 1961 |
my $logger = Log::Log4perl->get_logger(); |
| 1962 |
} |
| 1963 |
|
| 1964 |
then the get_logger() call will get a logger for the "MyL4pWrapper" |
| 1965 |
category, not for the package calling the wrapper class as in |
| 1966 |
|
| 1967 |
package UserPackage; |
| 1968 |
my $logger = MyL4pWrapper->get_logger(); |
| 1969 |
|
| 1970 |
To have the above call to get_logger return a logger for the |
| 1971 |
"UserPackage" category, you need to tell Log4perl that "MyL4pWrapper" is |
| 1972 |
a Log4perl wrapper class: |
| 1973 |
|
| 1974 |
use MyL4pWrapper; |
| 1975 |
Log::Log4perl->wrapper_register(__PACKAGE__); |
| 1976 |
|
| 1977 |
sub get_logger { |
| 1978 |
# Now gets a logger for the category of the calling package |
| 1979 |
my $logger = Log::Log4perl->get_logger(); |
| 1980 |
} |
| 1981 |
|
| 1982 |
This feature works both for Log4perl-relaying classes like the wrapper |
| 1983 |
described above, and for wrappers that inherit from Log4perl use |
| 1984 |
Log4perl's get_logger function via inheritance, alike. |
| 1985 |
|
| 1986 |
Access to Internals |
| 1987 |
The following methods are only of use if you want to peek/poke in the |
| 1988 |
internals of Log::Log4perl. Be careful not to disrupt its inner |
| 1989 |
workings. |
| 1990 |
|
| 1991 |
"Log::Log4perl->appenders()" |
| 1992 |
To find out which appenders are currently defined (not only for a |
| 1993 |
particular logger, but overall), a "appenders()" method is available |
| 1994 |
to return a reference to a hash mapping appender names to their |
| 1995 |
Log::Log4perl::Appender object references. |
| 1996 |
|
| 1997 |
Dirty Tricks |
| 1998 |
infiltrate_lwp() |
| 1999 |
The famous LWP::UserAgent module isn't Log::Log4perl-enabled. Often, |
| 2000 |
though, especially when tracing Web-related problems, it would be |
| 2001 |
helpful to get some insight on what's happening inside |
| 2002 |
LWP::UserAgent. Ideally, LWP::UserAgent would even play along in the |
| 2003 |
Log::Log4perl framework. |
| 2004 |
|
| 2005 |
A call to "Log::Log4perl->infiltrate_lwp()" does exactly this. In a |
| 2006 |
very rude way, it pulls the rug from under LWP::UserAgent and |
| 2007 |
transforms its "debug/conn" messages into "debug()" calls of loggers |
| 2008 |
of the category "LWP::UserAgent". Similarily, "LWP::UserAgent"'s |
| 2009 |
"trace" messages are turned into "Log::Log4perl"'s "info()" method |
| 2010 |
calls. Note that this only works for LWP::UserAgent versions < |
| 2011 |
5.822, because this (and probably later) versions miss debugging |
| 2012 |
functions entirely. |
| 2013 |
|
| 2014 |
Suppressing 'duplicate' LOGDIE messages |
| 2015 |
If a script with a simple Log4perl configuration uses logdie() to |
| 2016 |
catch errors and stop processing, as in |
| 2017 |
|
| 2018 |
use Log::Log4perl qw(:easy) ; |
| 2019 |
Log::Log4perl->easy_init($DEBUG); |
| 2020 |
|
| 2021 |
shaky_function() or LOGDIE "It failed!"; |
| 2022 |
|
| 2023 |
there's a cosmetic problem: The message gets printed twice: |
| 2024 |
|
| 2025 |
2005/07/10 18:37:14 It failed! |
| 2026 |
It failed! at ./t line 12 |
| 2027 |
|
| 2028 |
The obvious solution is to use LOGEXIT() instead of LOGDIE(), but |
| 2029 |
there's also a special tag for Log4perl that suppresses the second |
| 2030 |
message: |
| 2031 |
|
| 2032 |
use Log::Log4perl qw(:no_extra_logdie_message); |
| 2033 |
|
| 2034 |
This causes logdie() and logcroak() to call exit() instead of die(). |
| 2035 |
To modify the script exit code in these occasions, set the variable |
| 2036 |
$Log::Log4perl::LOGEXIT_CODE to the desired value, the default is 1. |
| 2037 |
|
| 2038 |
Redefine values without causing errors |
| 2039 |
Log4perl's configuration file parser has a few basic safety |
| 2040 |
mechanisms to make sure configurations are more or less sane. |
| 2041 |
|
| 2042 |
One of these safety measures is catching redefined values. For |
| 2043 |
example, if you first write |
| 2044 |
|
| 2045 |
log4perl.category = WARN, Logfile |
| 2046 |
|
| 2047 |
and then a couple of lines later |
| 2048 |
|
| 2049 |
log4perl.category = TRACE, Logfile |
| 2050 |
|
| 2051 |
then you might have unintentionally overwritten the first value and |
| 2052 |
Log4perl will die on this with an error (suspicious configurations |
| 2053 |
always throw an error). Now, there's a chance that this is |
| 2054 |
intentional, for example when you're lumping together several |
| 2055 |
configuration files and actually *want* the first value to overwrite |
| 2056 |
the second. In this case use |
| 2057 |
|
| 2058 |
use Log::Log4perl qw(:nostrict); |
| 2059 |
|
| 2060 |
to put Log4perl in a more permissive mode. |
| 2061 |
|
| 2062 |
Prevent croak/confess from stringifying |
| 2063 |
The logcroak/logconfess functions stringify their arguments before |
| 2064 |
they pass them to Carp's croak/confess functions. This can get in |
| 2065 |
the way if you want to throw an object or a hashref as an exception, |
| 2066 |
in this case use: |
| 2067 |
|
| 2068 |
$Log::Log4perl::STRINGIFY_DIE_MESSAGE = 0; |
| 2069 |
|
| 2070 |
eval { |
| 2071 |
# throws { foo => "bar" } |
| 2072 |
# without stringification |
| 2073 |
$logger->logcroak( { foo => "bar" } ); |
| 2074 |
}; |
| 2075 |
|
| 2076 |
EXAMPLE |
| 2077 |
A simple example to cut-and-paste and get started: |
| 2078 |
|
| 2079 |
use Log::Log4perl qw(get_logger); |
| 2080 |
|
| 2081 |
my $conf = q( |
| 2082 |
log4perl.category.Bar.Twix = WARN, Logfile |
| 2083 |
log4perl.appender.Logfile = Log::Log4perl::Appender::File |
| 2084 |
log4perl.appender.Logfile.filename = test.log |
| 2085 |
log4perl.appender.Logfile.layout = \ |
| 2086 |
Log::Log4perl::Layout::PatternLayout |
| 2087 |
log4perl.appender.Logfile.layout.ConversionPattern = %d %F{1} %L> %m %n |
| 2088 |
); |
| 2089 |
|
| 2090 |
Log::Log4perl::init(\$conf); |
| 2091 |
|
| 2092 |
my $logger = get_logger("Bar::Twix"); |
| 2093 |
$logger->error("Blah"); |
| 2094 |
|
| 2095 |
This will log something like |
| 2096 |
|
| 2097 |
2002/09/19 23:48:15 t1 25> Blah |
| 2098 |
|
| 2099 |
to the log file "test.log", which Log4perl will append to or create it |
| 2100 |
if it doesn't exist already. |
| 2101 |
|
| 2102 |
INSTALLATION |
| 2103 |
If you want to use external appenders provided with "Log::Dispatch", you |
| 2104 |
need to install "Log::Dispatch" (2.00 or better) from CPAN, which itself |
| 2105 |
depends on "Attribute-Handlers" and "Params-Validate". And a lot of |
| 2106 |
other modules, that's the reason why we're now shipping Log::Log4perl |
| 2107 |
with its own standard appenders and only if you wish to use additional |
| 2108 |
ones, you'll have to go through the "Log::Dispatch" installation |
| 2109 |
process. |
| 2110 |
|
| 2111 |
Log::Log4perl needs "Test::More", "Test::Harness" and "File::Spec", but |
| 2112 |
they already come with fairly recent versions of perl. If not, |
| 2113 |
everything's automatically fetched from CPAN if you're using the CPAN |
| 2114 |
shell (CPAN.pm), because they're listed as dependencies. |
| 2115 |
|
| 2116 |
"Time::HiRes" (1.20 or better) is required only if you need the |
| 2117 |
fine-grained time stamps of the %r parameter in |
| 2118 |
"Log::Log4perl::Layout::PatternLayout". |
| 2119 |
|
| 2120 |
Manual installation works as usual with |
| 2121 |
|
| 2122 |
perl Makefile.PL |
| 2123 |
make |
| 2124 |
make test |
| 2125 |
make install |
| 2126 |
|
| 2127 |
DEVELOPMENT |
| 2128 |
Log::Log4perl is still being actively developed. We will always make |
| 2129 |
sure the test suite (approx. 500 cases) will pass, but there might still |
| 2130 |
be bugs. please check <http://github.com/mschilli/log4perl> for the |
| 2131 |
latest release. The api has reached a mature state, we will not change |
| 2132 |
it unless for a good reason. |
| 2133 |
|
| 2134 |
Bug reports and feedback are always welcome, just email them to our |
| 2135 |
mailing list shown in the AUTHORS section. We're usually addressing them |
| 2136 |
immediately. |
| 2137 |
|
| 2138 |
REFERENCES |
| 2139 |
[1] Michael Schilli, "Retire your debugger, log smartly with |
| 2140 |
Log::Log4perl!", Tutorial on perl.com, 09/2002, |
| 2141 |
<http://www.perl.com/pub/a/2002/09/11/log4perl.html> |
| 2142 |
|
| 2143 |
[2] Ceki Gülcü, "Short introduction to log4j", |
| 2144 |
<http://logging.apache.org/log4j/1.2/manual.html> |
| 2145 |
|
| 2146 |
[3] Vipan Singla, "Don't Use System.out.println! Use Log4j.", |
| 2147 |
<http://www.vipan.com/htdocs/log4jhelp.html> |
| 2148 |
|
| 2149 |
[4] The Log::Log4perl project home page: <http://log4perl.com> |
| 2150 |
|
| 2151 |
SEE ALSO |
| 2152 |
Log::Log4perl::Config, Log::Log4perl::Appender, |
| 2153 |
Log::Log4perl::Layout::PatternLayout, |
| 2154 |
Log::Log4perl::Layout::SimpleLayout, Log::Log4perl::Level, |
| 2155 |
Log::Log4perl::JavaMap Log::Log4perl::NDC, |
| 2156 |
|
| 2157 |
AUTHORS |
| 2158 |
Please contribute patches to the project on Github: |
| 2159 |
|
| 2160 |
http://github.com/mschilli/log4perl |
| 2161 |
|
| 2162 |
Send bug reports or requests for enhancements to the authors via our |
| 2163 |
|
| 2164 |
MAILING LIST (questions, bug reports, suggestions/patches): |
| 2165 |
[email protected] |
| 2166 |
|
| 2167 |
Authors (please contact them via the list above, not directly): Mike |
| 2168 |
Schilli <[email protected]>, Kevin Goess <[email protected]> |
| 2169 |
|
| 2170 |
Contributors (in alphabetical order): Ateeq Altaf, Cory Bennett, Jens |
| 2171 |
Berthold, Jeremy Bopp, Hutton Davidson, Chris R. Donnelly, Matisse |
| 2172 |
Enzer, Hugh Esco, Anthony Foiani, James FitzGibbon, Carl Franks, Dennis |
| 2173 |
Gregorovic, Andy Grundman, Paul Harrington, Alexander Hartmaier, David |
| 2174 |
Hull, Robert Jacobson, Jason Kohles, Jeff Macdonald, Markus Peter, Brett |
| 2175 |
Rann, Peter Rabbitson, Erik Selberg, Aaron Straup Cope, Lars Thegler, |
| 2176 |
David Viner, Mac Yang. |
| 2177 |
|
| 2178 |
LICENSE |
| 2179 |
Copyright 2002-2013 by Mike Schilli <[email protected]> and Kevin Goess |
| 2180 |
<[email protected]>. |
| 2181 |
|
| 2182 |
This library is free software; you can redistribute it and/or modify it |
| 2183 |
under the same terms as Perl itself. |
| 2184 |
|