How do I supress log messages from external libraries, using log4j

谁说胖子不能爱 提交于 2019-12-24 08:17:04

问题


I am using log4j2 to do some logging for a project. My Loggers section in my config looks like this.

<Loggers>

    <!-- default logger -->
    <Root level="info">
        <AppenderRef ref="Console"/>
    </Root>

    <!-- only log warn/error/fatal for external libs -->
    <Logger name="org.cfg4j" level="warn" additivity="false">
        <AppenderRef ref="Console"></AppenderRef>
    </Logger>
    <Logger name="io.netty.util" level="warn" additivity="false">
        <AppenderRef ref="Console"></AppenderRef>
    </Logger>

</Loggers>

This doesn't seem to be having any effect as far as supressing the DEBUG level messages from io.netty.util

I googled "io.netty.util logging" and came up with this. It looks like there is a way to override the default logger

public abstract class InternalLoggerFactory {
private static volatile InternalLoggerFactory defaultFactory;

static {
    final String name = InternalLoggerFactory.class.getName();
    InternalLoggerFactory f;
    try {
        f = new Slf4JLoggerFactory(true);
        f.newInstance(name).debug("Using SLF4J as the default logging framework");
        defaultFactory = f;
    } catch (Throwable t1) {
        try {
            f = new Log4JLoggerFactory();
            f.newInstance(name).debug("Using Log4J as the default logging framework");
        } catch (Throwable t2) {
            f = new JdkLoggerFactory();
            f.newInstance(name).debug("Using java.util.logging as the default logging framework");
        }
    }

    defaultFactory = f;
}

I tried giving this a go, butI ran into a few issues. For one, my IDE (intellij) told me that Log4JLoggerFactory is deprecated. I proceeded, but then found out that the instance did not contain a method called "newInstance".

So, I'm a little confused on how to proceed with this. Is there a way for log4j to supress external libraries DEBUG/INFO level messages in the way that I am thinking?


回答1:


If the logger is defined in log4j 1.x api ( original version of the answer):

The problem is that log4j 1.x api don't use log4j2 property.

Add log4j-1.2-api.jar, as a log4j 1.x bridge, it should fix your problem.

But seems default loggerfactory of netty is Slf4JLoggerFactory, so waht actually needed are the slf4j bridges. slf4j-log4j12 to log4j 1.x, log4j-slf4j-impl to log4j2.x.



来源:https://stackoverflow.com/questions/44576327/how-do-i-supress-log-messages-from-external-libraries-using-log4j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!