From: <msc...@ao...> - 2002-11-21 07:24:27
|
Welcome to the Log::Log4perl recipe of the week. Today, we'll talk about customizing your loggers to include global data in all of your log messages: Say, you're writing a web application and want all your log messages to include the current client's IP address. Most certainly, you don't want to include it in each and every log message like in $logger->debug( $r->connection->remote_ip, " Retrieving user data from DB" ); do you? Instead, you want to set it in a global data structure and have Log::Log4perl include it automatically via a PatternLayout setting in the configuration file: log4perl.appender.FileApp.layout.ConversionPattern = \ %X{ip} %m%n The conversion specifier %X{ip} references an entry under the key "ip" in the global "MDC" (mapped diagnostic context) table, which you've set once via Log::Log4perl::MDC->put("ip", $r->connection->remote_ip); at the start of the request handler. Note that this is a *static* (class) method, there's no logger object involved. You can use this method with as many key/value pairs as you like as long as you reference them under different names. The mappings are stored in a global hash table within Log::Log4perl. Luckily, because the thread model in 5.8.0 doesn't share global variables between threads unless they're explicitly marked as such, there's no problem with multi-threaded environments like mod_perl. For more details on the MDC, please refer to the "Mapped Diagnostic Context (MDC)" section in the Log::Log4perl manpage and Log::Log4perl::MDC. As always, this recipe is going to be archived in the Log::Log4perl FAQ. Have fun! -- -- Mike ############################ # Mike Schilli # # log...@pe... # # http://perlmeister.com # # log4perl.sourceforge.net # ############################ |