Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zudsniper/9e1edfcefd157e9f65011ff4804f162a to your computer and use it in GitHub Desktop.
Save zudsniper/9e1edfcefd157e9f65011ff4804f162a to your computer and use it in GitHub Desktop.
1. Add dependecy:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
</dependency>
2.Create config file for log4j (https://logging.apache.org/log4j/2.x/manual/configuration.html).
I prefer log4j2-test.properties because according documentation this format will look second, after configFile:
'If no system property is set the properties ConfigurationFactory will look for log4j2-test.properties in the classpath.'
---------------------------------------------------------------
appenders=console
appender.console.type=Console
appender.console.name=STDOUT
appender.console.layout.type=PatternLayout
appender.console.layout.pattern=%highlight{[%d{HH:mm:ss:SSS}] [%p] [%c{1}:%L] - %m%n%throwable}{FATAL=white, ERROR=red, WARN=yellow, INFO=grey, DEBUG=green, TRACE=Cyan}
rootLogger.level=info
rootLogger.appenderRefs=stdout
rootLogger.appenderRef.stdout.ref=STDOUT
---------------------------------------------------------------
3. Create slf4j logger object (or use lombok annotation @Slf4j):
private static final Logger log = org.slf4j.LoggerFactory.getLogger(ClassName.class);
4. Add to IDEA configuration templates (Run->Edit configurations...) VM option: -Dlog4j.skipJansi=false
5. Enjoy!
p.s. log4j2.xml example
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Properties>
<Property name="log4j.level" value="INFO" />
<Property name="log4j.appender" value="file" />
</Properties>
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout
pattern="%highlight{%d{yyyy-MM-dd HH:mm:ss} %-5p (%c{1}:%L) - %m%n%throwable}{FATAL=white, ERROR=red, WARN=yellow, INFO=grey, DEBUG=green, TRACE=Cyan}"/>
</Console>
<File name="file" fileName="target/.logs/events.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>
</File>
</Appenders>
<Loggers>
<Root>
<AppenderRef ref="${sys:log4j.appender}" level="${sys:log4j.level}"/>
</Root>
</Loggers>
</Configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment