To include Log4j2 in your project, include below dependency in your project pom.xml:
<
dependency
>
<
groupId
>org.apache.logging.log4j</
groupId
>
<
artifactId
>log4j-api</
artifactId
>
<
version
>2.6.1</
version
>
</
dependency
>
<
dependency
>
<
groupId
>org.apache.logging.log4j</
groupId
>
<
artifactId
>log4j-core</
artifactId
>
<
version
>2.6.1</
version
>
</
dependency
>
Log4j2.xml for logging into Console
You can use below log4j2.xml
file logging output into console. Please note that if no configuration file could be located then DefaultConfiguration
will be used. This also causes logging output to go to the console.
<? xml version = "1.0" encoding = "UTF-8" ?> < Configuration status = "INFO" > < Appenders > < Console name = "console" target = "SYSTEM_OUT" > < PatternLayout pattern = "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" /> </ Console > </ Appenders > < Loggers > < Root level = "debug" additivity = "false" > < AppenderRef ref = "console" /> </ Root > </ Loggers > </ Configuration > |
log4j2.xml for logging into rolling files
You can use below log4j2.xml
file logging output into date based rolling files – along with console.
<? xml version = "1.0" encoding = "UTF-8" ?> < Configuration status = "warn" > < Properties > < Property name = "basePath" >C:\\logs</ Property > </ Properties > < Appenders > < RollingFile name = "fileLogger" fileName = "${basePath}/app-info.log" filePattern = "${basePath}/app-info-%d{yyyy-MM-dd}.log" > < PatternLayout > < pattern >[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</ pattern > </ PatternLayout > < Policies > < TimeBasedTriggeringPolicy interval = "1" modulate = "true" /> </ Policies > </ RollingFile > < Console name = "console" target = "SYSTEM_OUT" > < PatternLayout pattern = "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" /> </ Console > </ Appenders > < Loggers > < Logger name = "com.howtodoinjava" level = "debug" additivity = "true" > < appender-ref ref = "fileLogger" level = "debug" /> </ Logger > < Root level = "debug" additivity = "false" > < appender-ref ref = "console" /> </ Root > </ Loggers > </ Configuration > |
log4j2.xml example
Let’s write a java class and write few log statements to verify that logs are appreaing in console and log file as well. It logs different log levels to different logs
package com.howtodoinjava.log4j2.examples; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Log4j2HelloWorldExample { private static final Logger LOGGER = LogManager.getLogger(Log4j2HelloWorldExample. class .getName()); public static void main(String[] args) { LOGGER.debug( "Debug Message Logged !!!" ); LOGGER.info( "Info Message Logged !!!" ); LOGGER.error( "Error Message Logged !!!" , new NullPointerException( "NullError" )); } } |
Leave a Reply