Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SLF4J Log Level as an argument [duplicate]

We are looking to use SLF4J, but one thing we found was that you can't specify the level as an argument, i.e

Logger.log(Level.INFO, "messsage");

You have to do this

logger.info("message");

this prevents being able to pass everything through a method, so you can tack other properties to all log messages in a class.

public class Test
{
    public Test(SomeObj obj)
    {
       log(Level.INFO, "message");
    }

    public void anotherMethod()
    {
       log(Level.DEBUG, "another message");
    }
    private void log(Level level, String message)
    {
        logger.log(level, message + obj.someString());
    }
}

Is there a way to achieve this using SLF4j ?

like image 294
marchaos Avatar asked Sep 30 '10 14:09

marchaos


People also ask

How do you change the log level in SLF4J?

When using log4j, the Logger. log(Priority p, Object message) method is available and can be used to log a message at a log level determined at runtime. We're using this fact and this tip to redirect stderr to a logger at a specific log level. slf4j doesn't have a generic log() method that I can find.

What is the default logging level in SLF4J?

Spring Boot makes use of Apache Commons' Logging for its system logs by default. Additionally, by default you can use any of the logging frameworks under the SLF4J API such as Logback (which is the default), Log4J2, and Java Util Logging in Spring Boot.

How do you pass a log level in Java?

Logger setLevel() method in Java with Examples setLevel() method of a Logger class used to set the log level to describe which message levels will be logged by this logger. The level we want to set is passed as a parameter. Message levels lower than passed log level value will be discarded by the logger.

Why log4j is better than SLF4J?

Comparison SLF4J and Log4j 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. However, it is always difficult to prefer one between the two.


2 Answers

Write a wrapper around the slf4j call and create your own enum for the six log levels. Then in your wrapper, use a switch to call the correct slf4j call.

void myLog(Level level, String message)
{
  switch (level)
  {
  case FATAL:
    log.fatal(message);
    break;
  case ERROR:
    log.error(message);
    break;
  ....
  }
}
like image 175
Starkey Avatar answered Oct 31 '22 02:10

Starkey


The answer is No. Refer to this discussion.

like image 38
Raghuram Avatar answered Oct 31 '22 03:10

Raghuram