Why Purpose Slf4j Over Log4j For Logging Inward Java

Every Java programmers know that logging is critical for whatever Java application, peculiarly server-side application, together with many of them are already familiar amongst diverse logging libraries e.g. java.util.logging, Apache log4j, logback, but if yous don't know close SLF4J, Simple logging facade for Java,  together with hence it's fourth dimension to larn together with travel SLF4J inward your project. In this Java article, nosotros volition larn 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 retrieve anything I accept writing close logging. Anyway, let’s acquire dorsum to the topic, on opposite to all those logging libraries, in that location is a major divergence betwixt them together with SLF4J. SLF4J or Simple logging Facade for Java is non actually a logging implementation, instead, it's an abstraction layer, which allows yous to travel whatever logging library inward the back-end. If yous are writing API or utility library, which tin live used internally or externally, together with hence yous actually don't desire that whatever client, which uses your library, should every bit good stick amongst your pick of logging library. 

Suppose, if a projection is already using log4j, together with yous included a library say Apache Active MQ, which has dependency on logback, roughly other logging library, together with hence yous ask to include them every bit well, but if Apache Active MQ uses SL4J, yous tin choke on amongst your logging library, without hurting of adding together with maintaining novel logging framework. 

In curt SLF4J brand your code independent of whatever item logging API, which is expert think for populace API developers. Though persuasion of abstracting logging library is non novel together with Apache common logging is already using it, but at nowadays SLF4J is chop-chop becoming an criterion for logging inward Java world. 

Let's run into duad of to a greater extent than argue to travel SLF4J over log4j, logback or java.util.logging.



Prefer SLF4J over Log4J, logback together with java.util.Logging

Every Java programmers know that logging is critical for whatever Java application Why travel 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 whatever item logging library, which powerfulness require dissimilar configuration than yous already have, together with innovate to a greater extent than maintenance headache. But apart from that, in that location is i to a greater extent than characteristic of SLF4J API, which convinced me to travel SL4J over my long fourth dimension favorite Log4j, that is know every bit house holder together with 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 solely cut down lot of String concatenation inward your code, but every bit good terms of creating String object. This is truthful fifty-fifty if yous powerfulness non ask that, depending upon your log aeroplane inward production environs e.g. String concatenation on DEBUG together with INFO levels. Since Strings are immutable together with they are created inward String pool, they eat heap memory together with 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 aeroplane inward production. By using SLF4J, yous tin defer String creation at runtime, which agency solely required Strings volition live created. If yous accept been using log4j together with hence yous already familiar amongst a workaround of putting debug declaration within if() condition, but SLF4J placeholders are much amend than that.

This is how yous would create inward Log4j, but sure enough this is non fun together with cut down readability of code yesteryear adding unnecessary boiler-plate code.


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


On the other manus if yous travel SLF4J, yous tin acquire same lawsuit inward much concise format every bit shown below :


logger.debug("Processing merchandise amongst id: {} together with symbol : {} ", id, symbol);


In SLF4J, nosotros don't ask String concatenation together with don't incur terms of temporary non ask String. Instead, nosotros write log message inward a template format amongst placeholder together with provide actual value every bit parameters. You powerfulness live thinking close what if I accept multiple parameters, good yous tin either travel variable arguments version of log methods or overstep them every bit Object array. This is actually convenient together with efficient way of logging. Remember, before generating lastly String for logging message, this method cheque if a item log aeroplane is enabled or not, which non solely cut down retention consumption but every bit good 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 aeroplane 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 every bit good worth knowing that logging has severe behaviour on on performance of application, together with it's ever advised to solely mandatory logging inward production environment.

How to travel SLF4J amongst Log4J for logging

Apart from to a higher house benefits, I think in that location is i caveat though, inward club to travel SLF4J yous non solely ask to include SLF4J API Jar e.g. slf4j-api-1.6.1.jar, but every bit good companion JAR, depending upon which logging library, yous are using inward backend. Suppose If yous desire to use SLF4J, Simple Logging Facade for Java,  along amongst Lo4J, yous ask to include next jars inward your classpath, depending upon which version of SLF4J together with log4J yous 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 yous are using Maven to mange dependency inward your project, yous tin but include SLF4J JAR, together with maven volition include it's subject companion JAR. In club to travel Log4J along amongst SLF4J, yous 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 yous are interested inward using variable declaration version of logger methods, than include SLF4J 1.7 version.

Summary

To summarize this post, I would advise next reasons are expert plenty to select SLF4J over Log4j, common logging, logback or java.util.logging directly.

1) Using SLF4J inward your opened upwards beginning library or internal library, volition acquire inward independent of whatever item logging implementation, which agency no ask to handle 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 yesteryear removing checks prevarication isDebugEnabled(), isInfoEnabled() etc.

3) By using SLF4J logging method, yous defer terms of constructing logging messages (String), until yous ask it, which is both retention together with CPU efficient.

4) As a side note, less release of temporary strings agency less piece of job for Garbage Collector, which agency amend throughput together with surgery for your application.

These advantages are but tip of iceberg, yous volition larn close to a greater extent than benefits, when yous offset using SL4J together with reading close it.  I strongly suggest, whatever novel code evolution inward Java, should travel SLF4J for logging over whatever other logging API including log4J.


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

Komentar

Postingan populer dari blog ini

2 Ways To Banking Concern Tally If A String Is Rotation Of Other Inward Java?

How To Convert String To Integer To String Inward Coffee Amongst Example

How To Induce Chrome, Firefox Blurry, Over Bright, Fading Afterwards Windows Ten Update