Saturday 17 October 2015

Log4j2: Flow tracing

Logger class provides entry() and exit() methods that are useful for following the execution path of applications.

void entry()
void entry(Object... params)
Usually entry method placed at the beginning of a method, can be called by passing zero/more parameters. The entry() method logs with a level of TRACE.

The exit() method should be placed before any return statement or as the last statement of methods without a return.

void exit()
Logs exit from a method.

<R> R exit(R result)
Logs exiting from a method with the result.
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG" monitorInterval="30">
 <Appenders>
  <Console name="my_console_appender" target="SYSTEM_OUT">
   <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
  </Console>
 </Appenders>
 <Loggers>
  <Root level="trace">
   <AppenderRef ref="my_console_appender" />
  </Root>
 </Loggers>
</Configuration>


package log4j_tutorial;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class HelloWorld {
 private static final Logger logger = LogManager.getLogger();

 public static void hello() {
  logger.entry();
  System.out.println("Hello");
  logger.exit();
 }

 public static String helloMessage(String name) {
  logger.entry(name);
  String message = "hello " + name;
  return logger.exit(message);
 }

 public static void main(String args[]) {
  hello();
  helloMessage("krishna");
 }
}

Output
10:04:41.616 [main] TRACE log4j_tutorial.HelloWorld - entry
Hello
10:04:41.617 [main] TRACE log4j_tutorial.HelloWorld - exit
10:04:41.617 [main] TRACE log4j_tutorial.HelloWorld - entry params(krishna)
10:04:41.617 [main] TRACE log4j_tutorial.HelloWorld - exit with(hello krishna)


If you change the log level from trace to higher levels, entry and exit information will not print in console.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment