Why Purpose Slf4j Over Log4j For Logging Inwards Java

Advertisement

Masukkan script iklan 970x90px

Why Purpose Slf4j Over Log4j For Logging Inwards Java

Rabu, 06 Januari 2021

Every Java programmers know that logging is critical for whatsoever Java application, particularly server-side application, in addition to many of them are already familiar amongst diverse logging libraries e.g. java.util.logging, Apache log4j, logback, but if you lot don't know most SLF4J, Simple logging facade for Java,  in addition to thus it's fourth dimension to acquire in addition to purpose SLF4J inward your project. In this Java article, nosotros volition acquire why using SLF4J is amend than using log4j or java.util.logging. It’s been a long time, since I wrote 10 logging tips for Java programmer,I don’t think anything I accept writing most logging. Anyway, let’s acquire dorsum to the topic, on reverse to all those logging libraries, at that spot is a major divergence betwixt them in addition to SLF4J. SLF4J or Simple logging Facade for Java is non actually a logging implementation, instead, it's an abstraction layer, which allows you lot to purpose whatsoever logging library inward the back-end. If you lot are writing API or utility library, which tin hold upwards used internally or externally, in addition to thus you lot actually don't desire that whatsoever client, which uses your library, should besides stick amongst your choice of logging library. 

Suppose, if a projection is already using log4j, in addition to you lot included a library say Apache Active MQ, which has dependency on logback, roughly other logging library, in addition to thus you lot involve to include them every bit well, but if Apache Active MQ uses SL4J, you lot tin choke along amongst your logging library, without hurting of adding in addition to maintaining novel logging framework. 

In brusk SLF4J brand your code independent of whatsoever item logging API, which is skillful think for world API developers. Though sentiment of abstracting logging library is non novel in addition to Apache green logging is already using it, but at nowadays SLF4J is chop-chop becoming an touchstone for logging inward Java world. 

Let's run across couplet of to a greater extent than argue to purpose SLF4J over log4j, logback or java.util.logging.



Prefer SLF4J over Log4J, logback in addition to java.util.Logging

Every Java programmers know that logging is critical for whatsoever Java application Why purpose SLF4J over Log4J for logging inward Java
As I said earlier, chief motivation of using SLF4J inward your code to write log statements is, to brand your program, independent of whatsoever item logging library, which mightiness require unlike configuration than you lot already have, in addition to innovate to a greater extent than maintenance headache. But apart from that, at that spot is i to a greater extent than characteristic of SLF4J API, which convinced me to purpose SL4J over my long fourth dimension favorite Log4j, that is know every bit house holder in addition to represented every bit {} inward code. Placeholder is pretty much same every bit %s inward format() method of String, because it acquire substituted  by actual string supplied at runtime. This non alone trim lot of String concatenation inward your code, but besides toll of creating String object. This is truthful fifty-fifty if you lot mightiness non involve that, depending upon your log score inward production surroundings e.g. String concatenation on DEBUG in addition to INFO levels. Since Strings are immutable in addition to they are created inward String pool, they eat heap memory in addition to most of the fourth dimension they are non needed e.g. an String used inward DEBUG declaration is non needed, when your application is running on ERROR score inward production. By using SLF4J, you lot tin defer String creation at runtime, which agency alone required Strings volition hold upwards created. If you lot accept been using log4j in addition to thus you lot already familiar amongst a workaround of putting debug declaration within if() condition, but SLF4J placeholders are much amend than that.

This is how you lot would create inward Log4j, but sure enough this is non fun in addition to trim readability of code past times adding unnecessary boiler-plate code.


if (logger.isDebugEnabled()) {     logger.debug("Processing merchandise amongst id: " + id + " symbol: " + symbol); }


On the other paw if you lot purpose SLF4J, you lot tin acquire same resultant inward much concise format every bit shown below :


logger.debug("Processing merchandise amongst id: {} in addition to symbol : {} ", id, symbol);


In SLF4J, nosotros don't involve String concatenation in addition to don't incur toll of temporary non involve String. Instead, nosotros write log message inward a template format amongst placeholder in addition to render actual value every bit parameters. You mightiness hold upwards thinking most what if I accept multiple parameters, good you lot tin either purpose variable arguments version of log methods or overstep them every bit Object array. This is actually convenient in addition to efficient way of logging. Remember, before generating in conclusion String for logging message, this method cheque if a item log score is enabled or not, which non alone trim retentiveness consumption but besides CPU fourth dimension involved for executing those String concatenation teaching inward advance. Here is the code of SLF4J logger method from it's Log4j Adapter cast Log4jLoggerAdapter from slf4j-log4j12-1.6.1.jar.


public void debug(String format, Object arg1, Object arg2) {     if (logger.isDebugEnabled()) {       FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);       logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());     } }


It's besides worth knowing that logging has severe deport on on performance of application, in addition to it's ever advised to alone mandatory logging inward production environment.

How to purpose SLF4J amongst Log4J for logging

Apart from higher upwards benefits, I think at that spot is i caveat though, inward companionship to purpose SLF4J you lot non alone involve to include SLF4J API Jar e.g. slf4j-api-1.6.1.jar, but besides companion JAR, depending upon which logging library, you lot are using inward backend. Suppose If you lot desire to use SLF4J, Simple Logging Facade for Java,  along amongst Lo4J, you lot involve to include next jars inward your classpath, depending upon which version of SLF4J in addition to log4J you lot are using e.g.

 slf4j-api-1.6.1.jar - JAR for SLF4J API
 log4j-1.2.16.jar    - JAR for Log4J API
 slf4j-log4j12-1.6.1.jar - Log4J Adapter for SLF4J

If you lot are using Maven to mange dependency inward your project, you lot tin simply include SLF4J JAR, in addition to maven volition include it's subject companion JAR. In companionship to purpose Log4J along amongst SLF4J, you lot tin include next dependency inward your project's pom.xml

<dependency>         <groupId>org.slf4j</groupId>         <artifactId>slf4j-log4j12</artifactId>         <version>1.6.1</version> </dependency> <dependency>         <groupId>org.slf4j</groupId>         <artifactId>slf4j-log4j12</artifactId>         <version>1.6.1</version> </dependency> 

By the way, if you lot are interested inward using variable declaration version of logger methods, than include SLF4J 1.7 version.

Summary

To summarize this post, I would propose next reasons are skillful plenty to direct SLF4J over Log4j, green logging, logback or java.util.logging directly.

1) Using SLF4J inward your opened upwards origin library or internal library, volition arrive independent of whatsoever item logging implementation, which agency no involve to create create multiple logging configuration for multiple libraries, your customer volition going to appreciate this.

2) SLF4J provides house holder based logging, which improves readability of code past times removing checks prevarication isDebugEnabled(), isInfoEnabled() etc.

3) By using SLF4J logging method, you lot defer toll of constructing logging messages (String), until you lot involve it, which is both retentiveness in addition to CPU efficient.

4) As a side note, less publish of temporary strings agency less function for Garbage Collector, which agency amend throughput in addition to functioning for your application.

These advantages are simply tip of iceberg, you lot volition acquire most to a greater extent than benefits, when you lot foremost using SL4J in addition to reading most it.  I strongly suggest, whatsoever novel code evolution inward Java, should purpose SLF4J for logging over whatsoever other logging API including log4J.


Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!