Java – slf4j log level as a parameter

There is already an answer to this question: > setting log level of message at runtime in slf4j11

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

You have to

logger.info("message");

This prevents all content from being passed in one way, so you can paste other properties into all log messages in the 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 implement this using slf4j?

Solution

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

void myLog(Level level,String message)
{
  switch (level)
  {
  case FATAL:
    log.fatal(message);
    break;
  case ERROR:
    log.error(message);
    break;
  ....
  }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>