In log4j if we write
**logger.debug("Processing trade with id: " + id + " symbol: " + symbol);**
it will create String in string pool but when we use slf4j we use parameter based like this
**logger.debug("Processing trade with id: {} and symbol : {} ", id, symbol);**
So what is the difference between these two statement, slf4j will create String at run time or not ?
Key Differences Between Slf4j and Log4j 1. Ssl4j is just an abstraction or it provides an abstraction layer and we are not using it whereas Log4j is a logging framework that has different implementations. Appenders: they act as outputs while publishing the logging information to different destinations.
SLF4j is a logging facade, it doesn't do logging by itself instead depends on the logging component like LOG4j, Logback or JLogging. SLF4j is an API designed to give generic access to many logging frameworks.
SLF4J ship with a module called log4j-over-slf4j. It allows log4j users to migrate existing applications to SLF4J without changing a single line of code but simply by replacing the log4j. jar file with log4j-over-slf4j.
As such, using log4j 2. x, even via SLF4J does not mitigate the vulnerability. However, as mentioned already, log4j 1. x is safe with respect to CVE-2021-44228.
The difference is increase of performance, in log4j the string is concatenated every time the line is evaluated even if log level is lower than debug so the string will never be used.
slf4j, the string and parameters are passed through to the logger which only substitutes them if the log message is actually to be used.
Imagine code with debug statements every few lines, when in production and debug is disabled that is a huge amount of string manipulation that will never be used.
I would say to increase performance by reducing String concatenations
.
When you write this
"Processing trade with id: " + id + " symbol: " + symbol
You are creating the printing string manually.
When you write
"Processing trade with id: {} and symbol : {} ", id, symbol
-------^id------------^symbol---------
In the second way before printing internally slf4j
maintaind and generate a new string again with concatenation (Haven't check the source code,may be a StringBuilder
).
The {}
called as place holders and replace by the args passed by you.
From docs of sl4j
This form avoids superfluous string concatenation when the logger is disabled for the DEBUG level. However, this variant incurs the hidden (and relatively small) cost of creating an Object[] before invoking the method, even if this logger is disabled for DEBUG. The variants taking one and two arguments exist solely in order to avoid this hidden cost.
Read how to use the format :How to use java.String.format in Scala?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With