Set Dynamic Console Logging Level Using SLF4J

2019-08-23 05:04发布

I'm using slf4j logging facade over the jdk built in logger. I'm confused how to set the logging level using a ConsoleHandler for SLF4J.

public Class foo(){
   Logger log = Logger.getLogger(foo.class()) //logger from SLF
   public void run(){
       log.info("info")
    }
   private static void main(String[] args){
     ConsoleHandler con = new ConsoleHandeler(); //from java.util.logging
     con.setLevel(Level.OFF)
     run()
    }
   }


  >INFO: info

Shouldn't the info be turned off? I didn't want to set up a logging properties file because I want the user to input the level of logging they want from a command line interface. I only care about console appending. Is this similar to this: Using java.util.logging to log on the console

1条回答
贪生不怕死
2楼-- · 2019-08-23 05:52

Do not mix using SLF4J and a logging implementation. The idea of SLF4J is that you can switch the logger implementation by just replacing a jar and a config file. There will be no reference in your code to any logging impolementation (lkog4j, util logging, etc). Since SLF4J is a logging facade, you will be able to control only the log levels and what is being logged. Handlers etc are part of logging implementation.
You should leave the user to decide where to log, what level to log etc.

Apart from that; to disable console logging in util logger. Do

Get the root logger Logger logger = Logger.getLogger("");
get all its handlers logger.getHandlers();
iterate and check if any of it is instanceof ConsoleHandler
set level for that handler con.setLevel(Level.OFF)

In your main method you just created a new ConsoleHandler. It is not associated to any logger so nothing will happen.

查看更多
登录 后发表回答