Saturday 17 October 2015

Log4j2 : Console Appender: Writes output to system console


Appenders are responsible for delivering log messages to external world like files, database, console, socket etc., You can attach filters to appenders to filter the log messages, and formatters to format the log messages before sending them to destination.

Console appender writes log messages to either System.out (or) System.err.

Following are the parameters for Console appender.

Parameter
Type
Description
filter
Filter
Filters are used to filter the log events. Filters take the decision, whether to  log the event (or) not.
layout
Layout
Layout is used to format the log event. By default ‘"%m%n" ‘ pattern layout is used.
follow
boolean
Identifies whether the appender honors reassignments of System.out or System.err via System.setOut or System.setErr made after configuration.
name
String
Name of the appender
ignoreExceptions
boolean
If it set to false, then exceptions will be propagated to the caller. Default value is true.
target
String
Either "SYSTEM_OUT" or "SYSTEM_ERR", default is "SYSTEM_ERR".

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="info">
   <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 main(String args[]) {
  logger.trace("Trace Message!");
  logger.debug("Debug Message!");
  logger.info("Info Message!");
  logger.warn("Warn Message!");
  logger.error("Error Message!");
  logger.fatal("Fatal Message!");
 }
}

You can see following messages in console.

19:06:20.828 [main] INFO  log4j_tutorial.HelloWorld - Info Message!
19:06:20.828 [main] WARN  log4j_tutorial.HelloWorld - Warn Message!
19:06:20.828 [main] ERROR log4j_tutorial.HelloWorld - Error Message!
19:06:20.828 [main] FATAL log4j_tutorial.HelloWorld - Fatal Message!



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment