简体   繁体   English

从对象创建级别启用/禁用日志记录

[英]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.我将 slf4j 记录为 logback 之上的日志外观库。

Any suggestions are always welcome.任何建议总是受欢迎的。

You can use SimpleLogger for this:您可以为此使用SimpleLogger

  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.编辑:我使用下面的 Maven 依赖项来获取 SimpleLogger。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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