简体   繁体   English

围绕 log4j 记录器和 java.util.logging 的 java 包装器

[英]java wrapper around log4j logger and java.util.logging

I am writing a library.我正在写一个图书馆。 The library can be used by applications that use log4j loggers and java.util.logging loggers.该库可供使用 log4j 记录器和 java.util.logging 记录器的应用程序使用。

So, I wrote a quick wrapper class, that encapsulates both loggers.所以,我写了一个快速包装类,它封装了两个记录器。 I allow the application to set one or both loggers.我允许应用程序设置一个或两个记录器。 And in my library I use the encapsulated class to print to either logger.在我的库中,我使用封装的类打印到任一记录器。

My question is, since many threads can simultaneously be using the same instance of the wrapper class to log messages using the class' methods (for example: fatal() below), what steps should be taken to make these methods thread safe?我的问题是,由于许多线程可以同时使用包装类的同一个实例来使用类的方法(例如:下面的fatal())记录消息,应该采取哪些步骤来使这些方法线程安全?

public class MultiLogger {
    private static org.apache.log4j.Logger _log4jLogger = null;
    private static java.util.logging.Logger _javaUtilLogger = null;

    private MultiLogger () {
    }

    // log4j FATAL, log util SEVERE
    public void fatal (Object message) {
        if (_log4jLogger != null) {
            _log4jLogger.log("", Level.FATAL, message, null);
        }

        if (_javaUtilLogger != null) {
            _javaUtilLogger.severe((String) message);
        }
    }
    ...
}

Any other comments appreciated too.任何其他评论也表示赞赏。

Option 1: slf4j, as per comment on question.选项 1:slf4j,根据对问题的评论。

Option 2: cxf.apache.org has such a device in it.选项 2:cxf.apache.org 中有这样的设备。 We use it instead of slf4j because slf4j lacks internationalization support.我们使用它代替 slf4j,因为 slf4j 缺乏国际化支持。 You are welcome to grab the code.欢迎您获取代码。

See my comment:看我的评论:

You should check out slf4j before you proceed with this library.在继续使用此库之前,您应该先查看 slf4j。 It wraps all the major logging libraries and is very high quality.它包含了所有主要的日志库并且质量非常高。

But I presume that your wrapper class will be used in the same manner as the loggers that it wraps.但我认为您的包装类将以其包装的记录器相同的方式使用。 In that case, the wrapped classes should handle the synchronization for you.在这种情况下,包装类应该为您处理同步。

假设您只是使用如上所示的 log4j 和 util Loggers,我认为您不会遇到任何同步问题。

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

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