java logger到多个类和包中的一个文件 [英] java logger to one file over several classes and packages

查看:170
本文介绍了java logger到多个类和包中的一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何使用java.util.logging功能.所有教程都显示了如何从主类中登录到日志文件,但是我无法弄清楚如何在各个类中登录到一个文件.我有一个Web服务和一个Web服务客户端,我希望能够在使用Web服务客户端时在该Web服务上记录错误.

I'm trying to figure out how to use the java.util.logging features. All of the tutorials show how to log to a log file from the main class, but I cannot figure out how I can log to one file in various classes. I have a web service and a web service client and I'd like to be able to log errors on the web service while using the web service client.

我尝试创建一个记录器类,但最终得到38个空日志文件.我应该如何创建一个在Web服务的每个类中都调用过的记录器?该Web服务具有两个不同的程序包和各种类.

I tried creating a logger class but I ended up with 38 empty log files. How should I create one logger that's called in each of my classes on the web service? The web service has two different packages and various classes.

在搜索中,我遇到了创建单例记录器类的想法.我试图弄清楚如何实现它:

In my searching I've come across the idea for a singleton logger class. I'm trying to figure out how to implement it:

public class Logger{

private static Logger self = new Logger();

//empty private constructor
private Logger(){

}

//synchronized getInstance
public static synchronized Logger getInstance(){
    if (self == null)
        self = new Logger();
    return self;
}

//prevent cloning
public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException(); 
}

//synchronized logging
public synchronized void debug(String msg){

}
public synchronized void info(String msg){

}
public synchronized void fatal(String msg){

}

}

要在其他班级中调用它,我需要在每个班级中创建一个文件处理程序吗?

To call this in my other classes, would I need to create a filehandler in each class?

推荐答案

这就是在 FileHandler 添加到一个位于记录器层次结构根部的记录器,所有内容都将记录到该文件处理程序中.您必须提防处理程序也具有自己的日志级别.

That’s what the JDK logging framework has Handlers for. Add a FileHandler to a logger that is at the root of your logger hierarchy and everything will be logged to that file handler. You have to watch out for the fact that handlers have their own log levels, too.

因此,无需实现自己的日志记录框架.它已经在那里,而且已经很好. (如果您不喜欢JDK日志记录,请在JDK记录器中使用 Apache Commons Logging log4j的.)

So, no need to implement your own logging framework. It’s already there, and it’s already good. (And if you don’t like the JDK logging, use Apache Commons Logging with the JDK logger or log4j.)

这篇关于java logger到多个类和包中的一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆