log4j and weblogic: duplicate log messages

2019-04-30 03:10发布

I use log4j for logging in my project. Here is it's sample setup:

public class MyClass {
  private final Logger logger = Logger.getLogger(MyClass.class);

  public MyClass() {
    BasicConfigurator.configure();
    Logger.getLogger(MyClass.class).setLevel(Level.INFO);
  }

  ...

}

The problem is that on each next logger call it duplicates log messages (I mean on first call there is only 1 message, on second call there are 2 same messages, then there are 3 of them and so on). It seems that each time new logger's instance is created and used with all old instances.
How to avoid this problem? Thanks.

UPP. Tried to make it static,but it doesn't work anyway. I still get multiple log messages. Any ideas? Probably some Weblogic specific stuff?

4条回答
ゆ 、 Hurt°
2楼-- · 2019-04-30 03:39

If you make your Logger class static as suggested above, and then ensure that you're configuring log4j either via a -D system property at the JVM level or in the configuration of your application, you shouldn't have any issues. That call to parse configuration either at class load time or at instance creation time is unnecessary overhead.

log4j should only need to initialise configuration once - whether that's at the initialisation of the server, or at deployment of your application.

Is your project a web application?

Also, you can find out more about hooking into WebLogic Server's logging configuration here: http://download.oracle.com/docs/cd/E12840_01/wls/docs103/logging/logging_services.html

Hope that helps.

查看更多
别忘想泡老子
3楼-- · 2019-04-30 03:43

The issue lies in the BasicConfurator.configure() method. I had the exact same issue in my java project, and I'm not using WebLogic.

I moved my BasicConfigurator.configure() method from my beforeTest() to beforeClass(), and suddenly the issue went away.

@BeforeClass
public static void beforeClass() {
  BasicConfigurator.configure();
  GeoLogger.setLogLevel(Level.INFO);
}

@Before
public void beforeTest() {
  //BasicConfigurator.configure();
}

Hope that helps direct you to a solution.

查看更多
对你真心纯属浪费
4楼-- · 2019-04-30 03:45

try setting additivity false programmatically or in config.

    Logger.getLogger(MyClass.class).setAdditivity(false);

To me, that did the trick when I set it in log4j.xml

<logger name="com.stackoverflow.answers.gnat" additivity="false">
    <!-- note additivity value set above -->
    <level value="INFO"/>
    <appender-ref ref="knowledge"/>
    <appender-ref ref="reputation"/>
</logger>
查看更多
Anthone
5楼-- · 2019-04-30 03:47

Make the logger static

private static final Logger logger = Logger.getLogger(MyClass.class);

The key here is to create a Logger for each class, and not for each instance.

查看更多
登录 后发表回答