In log messages it is often need to pass application data which is common to a set of log messages. One example is to log a requestID of an API call which uniquely identifies all log messages belongs to processing a particular API call.
One approach is to pass the requestID in all log messages by appending the log message with requestID.
Another approach is to use log4Perl::MDC (Mapped Diagnostic Context). Using MDC we can store Thread Specific data and which can be accessed by logger. The thread specific data of a parent thread is accessible to its child thread as well.
Below program explains this.
Here we have set a Thread specific data key value pair using Log::Log4perl::MDC->put().
Logger will use the following configuration to print requestId from MDC to log message.
The log message will be as below.
2015-08-05 15:32:45,766|req00008|main|Received a request
One approach is to pass the requestID in all log messages by appending the log message with requestID.
Another approach is to use log4Perl::MDC (Mapped Diagnostic Context). Using MDC we can store Thread Specific data and which can be accessed by logger. The thread specific data of a parent thread is accessible to its child thread as well.
Below program explains this.
use Log::Log4perl;
Log::Log4perl::init("log4perl.conf");
method();
sub method {
Log::Log4perl::MDC->put("requestId","req00008");
my $logger = Log::Log4perl->get_logger("");
$logger->info("Received a request");
$logger->debug("Received a request");
}
Here we have set a Thread specific data key value pair using Log::Log4perl::MDC->put().
Logger will use the following configuration to print requestId from MDC to log message.
log4perl.rootLogger=TRACE, errorlog
log4perl.appender.errorlog=Log::Log4perl::Appender::File
log4perl.appender.errorlog.filename=c:/perl/log-dir/error.log
log4perl.appender.errorlog.mode=append
log4perl.appender.errorlog.Threshold = INFO
log4perl.appender.errorlog.layout=Log::Log4perl::Layout::PatternLayout
log4perl.appender.errorlog.layout.ConversionPattern=%d{ISO8601}|%X{requestId}|%C|%m%n
%X{requestId} - indicates that the information will be obtained from MDC with key ='requestId'
The log message will be as below.
2015-08-05 15:32:45,766|req00008|main|Received a request
Comments
Post a Comment