This is the widely used layout, format
log messages using pattern string. The format of the results is depend on the pattern
string you used.
Each conversion specifier starts with a
percent sign (%) and is followed by optional format modifiers and a conversion
character. The conversion character specifies the type of data, e.g. category,
priority, date, thread name. The format modifiers control such things as field
width, padding, left and right justification.
For Example,
pattern="%d{HH:mm:ss.SSS} [%t]
%-5level %logger{36} - %msg%n"
Go through following link for more
information about PatternLayout.
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="warn" name="MyApp" packages=""> <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[]) throws InterruptedException { int val1 = 10, val2 = 11, val3 = 12; logger.trace("val1={}, val2={}, val3={}", val1, val2, val3); logger.debug("val1={}, val2={}, val3={}", val1, val2, val3); logger.info("val1={}, val2={}, val3={}", val1, val2, val3); logger.warn("val1={}, val2={}, val3={}", val1, val2, val3); logger.error("val1={}, val2={}, val3={}", val1, val2, val3); logger.fatal("val1={}, val2={}, val3={}", val1, val2, val3); } }
Run
HelloWorld application, you will get following messages in console.
11:46:51.973 [main] INFO log4j_tutorial.HelloWorld - val1=10, val2=11, val3=12 11:46:51.974 [main] WARN log4j_tutorial.HelloWorld - val1=10, val2=11, val3=12 11:46:51.974 [main] ERROR log4j_tutorial.HelloWorld - val1=10, val2=11, val3=12 11:46:51.974 [main] FATAL log4j_tutorial.HelloWorld - val1=10, val2=11, val3=12
No comments:
Post a Comment