1Shares
  • Home  / 
  • Java
  •  /  SLF4J LOG4J2 Configuration

SLF4J LOG4J2 Configuration

By Daniel Vladimirov / a couple of months ago

Using the simple logging facade for Java (slf4j) with Apache log4j 2 is pretty straightforward and can be done literally in a minute. The slf4j allows you to plug in the desired logging framework at runtime, giving you the flexibility to change it when such a requirement is present. It’s a popular logging abstraction library and here is how you can use it, along with log4j 2 which is one of the popular logging java libraries.

 

Using Maven, you need to add a few dependencies.

  1. The slf4j-api is the simple logging facade library

To make it work with log4j 2, you need to add the so called binding library – log4j-slf4j-impl

The last two dependencies are the log4j implementation

  • log4j-api
  • log4j-core

Obtaining a logger in a class can be done by using an slf4j logger factory. If no binding is present on the classpath, the slf4j will default to a “no operation” mode and will simply not log anything, since the slf4j is just an abstraction, not an actual logger implementation.

At this point, running an application and trying to log something will throw an error, because we’re missing the log4j configuration. Log4j 2 supports multiple formats for its configuration – xml, json, yml, even programmatic configuration. This example will demonstrate the minimal xml configuration needed

On your classpath, if using maven you can use the resources folder, create a file – log4j2.xml

The file and its contents are self-explanatory.

Log4j 2 should be now ready in your application.

About the author

Daniel Vladimirov

Software engineer and founder of simplyprogram.com

Click here to add a comment

Leave a comment: