log4j 记录器和 java.util.logging 的 java 包装器
我正在写一个库。该库可供使用 log4j 记录器和 java.util.logging 记录器的应用程序使用。
因此,我编写了一个快速包装类,它封装了两个记录器。我允许应用程序设置一个或两个记录器。在我的库中,我使用封装的类来打印到任一记录器。
我的问题是,由于许多线程可以同时使用包装类的同一实例来使用类的方法(例如:下面的 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);
}
}
...
}
任何其他评论也表示赞赏。
I am writing a library. The library can be used by applications that use log4j loggers and java.util.logging loggers.
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?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
选项 1:slf4j,根据问题评论。
选项2:cxf.apache.org中有这样一个设备。我们使用它代替 slf4j,因为 slf4j 缺乏国际化支持。欢迎您获取代码。
Option 1: slf4j, as per comment on question.
Option 2: cxf.apache.org has such a device in it. We use it instead of slf4j because slf4j lacks internationalization support. You are welcome to grab the code.
看我的评论:
但我认为您的包装类将以与其包装的记录器相同的方式使用。在这种情况下,包装的类应该为您处理同步。
See my comment:
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(如上所示),我认为您不会遇到任何同步问题。
Provided that you're just using log4j and util Loggers as shown above, I don't think you'll run into any sync problems.