How to use log4j

2 minute read

Apache logging service

Apache logging service

log4j.properties

#######################################
# DEBUG, INFO, WARN, ERROR, FATAL
# file, stdout
#######################################
# rootLogger
log4j.rootLogger=INFO, file, stdout

# logger: Kafka
log4j.logger.org.apache.kafka=INFO, kafkaAppender

# logger: Spring Framework
log4j.logger.org.springframework=WARN
log4j.logger.org.springframework.transaction=WARN

#######################################
# Appenders
#######################################
# Appender Name: file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/info.log
log4j.appender.file.MaxFileSize=100MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%t] %p [%c] %x %m%n

# Appender Name: stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d] %p [%c] %m%n

# Appender Name: kafkaAppender
kafka.logs.dir=log
log4j.appender.kafkaAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.kafkaAppender.DatePattern='.'yyyy-MM-dd-HH
log4j.appender.kafkaAppender.File=${kafka.logs.dir}/server.log
log4j.appender.kafkaAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.kafkaAppender.layout.ConversionPattern=[%d] %p %m (%c)%n

log4j examples

// Add appender using log4j.properties appenders
Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
// or simply:
Logger logger = LogManager.getRootLogger();

// x and y refer to exactly the same Logger object.
Logger x = LogManager.getLogger("wombat");
Logger y = LogManager.getLogger("wombat");

Logger log = Logger.getLogger(ClassName.class);
Logger log = Logger.getLogger("ClassName");

// Write
logger.debug("message");
logger.info("message");
logger.warn("message");
logger.error("message");
logger.fatal("message");

log4j without properties

private static org.apache.log4j.RollingFileAppender mFileAppender = null;
private static org.apache.log4j.Logger logger = null;

// Open
if (mFileAppender == null) {
    // Add appender programmatically
    mFileAppender = new RollingFileAppender();
    mFileAppender.setName("fileLogger"); // rootLogger appender name
    mFileAppender.setFile(logFileName);
    mFileAppender.setLayout(new PatternLayout("%d %p [%c{1}] %x %m%n"));
    mFileAppender.setThreshold(Level.DEBUG);
    mFileAppender.setAppend(true);
    mFileAppender.activateOptions();

    logger = Logger.getRootLogger();
    logger.addAppender(mFileAppender);
}

// Close
if (mFileAppender != null) {
    mFileAppender.close();
    mFileAppender = null;
}

Pattern

  • %m: Outputs your message.
  • %p: Outputs the priority of the logging event.
  • %r: Outputs the number of milliseconds elapsed since the start of the application until the creation of the logging event.
  • %c: Outputs the category of the logging event. Example: For the category name “a.b.c”, the pattern %c{2} will output “b.c”. {2} means “output last two components of the dot-separated category name”. If no {n} is there, full Category name is output by default.
  • %t: Outputs the name of the thread that generated the logging event.
  • %x: Outputs the nested diagnostic context (NDC) associated with the thread that generated the logging event. Useful when multiple clients are handled by separate threads such as in Java servlets.
  • %n: Outputs the platform-dependent newline character(s). Preferable to specifying “\n” or “\r\n” etc.
  • %%: Outputs a single percent sign. WARNING: The patterns below will slow down the execution of your program somewhat. Avoid unless execution speed is not an issue.
  • %d: Outputs the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. Example: %d{HH:mm:ss,SSS} or %d{dd MMM yyyy HH:mm:ss,SSS}. If no date format specifier is given then ISO8601 format is assumed. The date format specifier admits the same syntax as the time pattern string of Java’s SimpleDateFormat which is slow. For faster performance, use %d{ISO8601}, %d{ABSOLUTE}, %d{RELATIVE} (millisecs since program start, fastest) or %d{DATE} which use log4j’s ISO8601DateFormat, AbsoluteTimeDateFormat, RelativeTimeDateFormat and DateTimeDateFormat date formatters respectively.
  • %l: Outputs source code location information. Shortcut for %C.%M(%F:%L).
  • %C: Outputs the fully-qualified class name of the caller issuing the logging request. Example: For the class name “org.apache.xyz.SomeClass”, the pattern %C{1} will output “SomeClass”. {1} means “output last one component of the fully-qualified class name”. If no {n} is there, full class name is output by default.
  • %M: Outputs the method name where the logging request was issued.
  • %F: Outputs the file name where the logging request was issued.
  • %L: Outputs the line number from where the logging request was issued.

Tags:

Categories:

Updated:

Leave a comment