Why Role 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 you lot don't know virtually SLF4J, Simple logging facade for Java,  together with thus it's fourth dimension to acquire together with role SLF4J inwards 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 recall anything I convey writing virtually logging. Anyway, let’s acquire dorsum to the topic, on opposite to all those logging libraries, in that location is a major departure 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 you lot to role whatever logging library inwards the back-end. If you lot are writing API or utility library, which tin live on used internally or externally, together with thus you lot actually don't desire that whatever client, which uses your library, should likewise stick amongst your alternative of logging library. 

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

In brusk SLF4J brand your code independent of whatever item logging API, which is skillful think for world API developers. Though regard of abstracting logging library is non novel together with Apache park logging is already using it, but at nowadays SLF4J is chop-chop becoming an measure for logging inwards Java world. 

Let's encounter twain of to a greater extent than argue to role 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 role SLF4J over Log4J for logging inwards Java
As I said earlier, master copy motivation of using SLF4J inwards your code to write log statements is, to brand your program, independent of whatever item logging library, which mightiness require dissimilar configuration than you lot 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 role SL4J over my long fourth dimension favorite Log4j, that is know equally house holder together with represented equally {} inwards code. Placeholder is pretty much same equally %s inwards format() method of String, because it acquire substituted  by actual string supplied at runtime. This non entirely trim lot of String concatenation inwards your code, but likewise terms of creating String object. This is truthful fifty-fifty if you lot mightiness non withdraw that, depending upon your log marker inwards production surroundings e.g. String concatenation on DEBUG together with INFO levels. Since Strings are immutable together with they are created inwards String pool, they swallow heap memory together with most of the fourth dimension they are non needed e.g. an String used inwards DEBUG declaration is non needed, when your application is running on ERROR marker inwards production. By using SLF4J, you lot tin defer String creation at runtime, which agency entirely required Strings volition live on created. If you lot convey been using log4j together with 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 produce inwards Log4j, but sure enough this is non fun together with trim 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 you lot role SLF4J, you lot tin acquire same trial inwards much concise format equally shown below :


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


In SLF4J, nosotros don't withdraw String concatenation together with don't incur terms of temporary non withdraw String. Instead, nosotros write log message inwards a template format amongst placeholder together with render actual value equally parameters. You mightiness live on thinking virtually what if I convey multiple parameters, good you lot tin either role variable arguments version of log methods or top them equally Object array. This is actually convenient together with efficient way of logging. Remember, before generating in conclusion String for logging message, this method banking concern check if a item log marker is enabled or not, which non entirely trim retentivity consumption but likewise CPU fourth dimension involved for executing those String concatenation education inwards advance. Here is the code of SLF4J logger method from it's Log4j Adapter shape 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 likewise worth knowing that logging has severe touching on on performance of application, together with it's e'er advised to entirely mandatory logging inwards production environment.

How to role SLF4J amongst Log4J for logging

Apart from higher upward benefits, I think in that location is i caveat though, inwards club to role SLF4J you lot non entirely withdraw to include SLF4J API Jar e.g. slf4j-api-1.6.1.jar, but likewise companion JAR, depending upon which logging library, you lot are using inwards backend. Suppose If you lot desire to use SLF4J, Simple Logging Facade for Java,  along amongst Lo4J, you lot withdraw to include next jars inwards your classpath, depending upon which version of SLF4J together with 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 inwards your project, you lot tin simply include SLF4J JAR, together with maven volition include it's subject companion JAR. In club to role Log4J along amongst SLF4J, you lot tin include next dependency inwards 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 inwards using variable declaration version of logger methods, than include SLF4J 1.7 version.

Summary

To summarize this post, I would advise next reasons are skillful plenty to pick out SLF4J over Log4j, park logging, logback or java.util.logging directly.

1) Using SLF4J inwards your opened upward root library or internal library, volition arrive independent of whatever item logging implementation, which agency no withdraw to acquire by 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, you lot defer terms of constructing logging messages (String), until you lot withdraw it, which is both retentivity together with CPU efficient.

4) As a side note, less lay out of temporary strings agency less move for Garbage Collector, which agency amend throughput together with functioning for your application.

These advantages are simply tip of iceberg, you lot volition acquire virtually to a greater extent than benefits, when you lot get-go using SL4J together with reading virtually it.  I strongly suggest, whatever novel code evolution inwards Java, should role 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!


Sumber https://javarevisited.blogspot.com/

0 Response to "Why Role Slf4j Over Log4j For Logging Inward Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel