Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logger format and throwable, slf4j, arguments [duplicate]

Tags:

In the process of converting some old loggers from String.format to the newer slf4j {} variant, I stumbled upon this case:

logger.error(String.format("%s ... %s ... %s", ...), e); 

I would like to use only {} and remove the String format, however, the logger method signature which includes the throwable is:

error(String msg, Throwable t)

So I do have to keep the String.format in this case ?!

Why is there no:

error(Throwable t, String format, Object... arguments)

like image 463
Christophe Roussy Avatar asked Jul 12 '17 09:07

Christophe Roussy


People also ask

Is Log4j and SLF4J same?

Unlike log4j, SLF4J (Simple Logging Facade for Java) is not an implementation of logging framework, it is an abstraction for all those logging frameworks in Java similar to log4J. Therefore, you cannot compare both.

What logger does SLF4J use?

SLF4J stands for Simple Logging Facade for Java. It provides a simple abstraction of all the logging frameworks. It enables a user to work with any of the logging frameworks such as Log4j, Logback, JUL (java. util.

What is SLF4J default logger?

The SLF4J or the Simple Logging Facade for Java is an abstraction layer for various Java logging frameworks, like Log4j 2 or Logback. This allows for plugging different logging frameworks at deployment time without the need for code changes.

How do I turn off Info logs in SLF4J?

To disable this behavior, you must add a logback configuration file called logback. xml in your java classpath root. You can download this minimal logback. xml file and add it in the src/main/resources directory for a maven project or beside fr directory for a simple java project.


1 Answers

As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter.

So, writing (in SLF4J version 1.6.x and later)

logger.error("one two three: {} {} {}", "a", "b",            "c", new Exception("something went wrong")); 

http://www.slf4j.org/faq.html#paramException:

"Yes, as of SLF4J 1.6.0, but not in previous versions. The SLF4J API supports parametrization in the presence of an exception, assuming the exception is the last parameter."

like image 103
Mathias G. Avatar answered Oct 13 '22 01:10

Mathias G.