Log4sh:Examples 1.3

From FeProductWiki

Jump to: navigation, search

Examples and Workarounds for log4sh 1.3

Contents

Work around for limited %d in PatternLayout

As of log4sh-1.3.4, custom date and time patterns are not supported in the PatternLayout when using the %d conversion character. The only date format provided is the ISO 8601 date format which gives output similar to "2006-07-21 14:22:40". If a custom date format is needed, then a workaround can be employed.

To work around the limitation of the %d conversion character limitation, the %X conversion character must be used. It allows for custom environment variables to be inserted into a pattern. To insert a custom date or time, the environment variable must be updated before each call to one of the logging functions, and the environment variable must be included in the pattern.

Override the logger_*() functions

The various logger_*() functions (e.g. logger_info()) are actually just wrappers around the log() function, and they are easy to override. Below is a sample override for the logger_info() function. Note: when overriding these functions, the overridden functions must come after the sourcing of log4sh into the shell script.

This function will set the mdcDT environment variable to the current date/time (e.g. "21.07.06 14:31").

logger_info()
{
  mdcDT=`date "+%d.%m.%y %H:%M"`
  log INFO "$@"
}

Note that each of logger_*() functions need to be overridden to support this new functionality.

Update the PatternLayout

The appender needs a custom PatternLayout to support the custom date/time format. In this example, we are changing the mySTDERR appender layout to a PatternLayout and setting a custom layout for that appender. The resultant output will look just like the default PatternLayout '%d %p - %m%n', but the date will be in the format defined by the logger_info() function.

In code, this can be done as follows:

appender_setLayout mySTDERR PatternLayout
appender_setPattern mySTDERR '%X{mdcDT} %p - %m%n'

In a properties file, this can be done as follows:

log4sh.appender.mySTDERR.layout = PatternLayout
log4sh.appender.mySTDERR.layout.ConversionPattern = '%X{mdcDT} %p - %m%n'

Perform logging

Logging should happen as normal.

# log message at INFO level
logger_info "my message"

You should have seen output similar to the following:

21.07.06 14:39 INFO - my message
Personal tools
related