简体   繁体   中英

enable/disable logging from Object creation level

I am stuck in this problem for a while :

I have a class and it has some functions and also has some logging statements written inside of it. I want to enable/disable logging while creation an object of that particular class by passing some arguments in constructor. Would it be possible.

I am logging slf4j as my logging façade library on top of logback.

Any suggestions are always welcome.

You can use SimpleLogger for this:

  public class Test {

    private static final Logger LOGGER = LoggerFactory.getLogger(Test.class);

    public Test(String logLevel) {
        //
        System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, logLevel);
    }
}

And then you can use constructor like :

Test ref = new Test("info");  // for setting info level

Test ref1 = new Test("debug");  // for setting debug level.

This way you can change logger levels. Let me know if this is of any help.

Edit: I used below maven dependency to get SimpleLogger.

<dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
        </dependency> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM