enable/disable logging from Object creation level

Viewed 44

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.

1 Answers

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> 
Related