如何在Web应用程序中使用java.util.logger? [英] How to use java.util.logger in a web application?

查看:102
本文介绍了如何在Web应用程序中使用java.util.logger?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Web应用程序中使用记录器。我已经添加了FileHandler来将日志写入文件。现在,我需要在项目中的其他类/ servlet中使用相同的处理程序,以便将来自所有类的日志写入同一文本文件。
如何实现这一目标?

I'm trying to use a logger across a web application. I have added the FileHandler to write the log into file. Now, I need to use the same handler across other classes/servlets in the project, so that logs from all classes are written to same text file. How can I achieve this?

/***
 * Initialize a logger
 */
public static Logger logger;
static {
    try {
      FileHandler fh = new FileHandler("log.txt", true);
      fh.setFormatter(new SimpleFormatter());
      logger = Logger.getLogger(MyClass.class.getName());
      logger.addHandler(fh);
    }
    catch (IOException e) {
      e.printStackTrace();
    }
}

我是否需要初始化记录器并添加处理程序每个班级如上面的代码?还有其他技巧吗?

Do I need to initialize the logger and add handler in every class as in above code? Any other techniques?

推荐答案

我考虑使用Log4J等日志框架。

I'd consider using a logging framework such as Log4J.

使用它可以归结为配置appender(例如FileAppender)和日志级别在中央文件(.xml或.properties)和每个需要定义记录器的类中你只需 Log l = LogFactory.getLog(clazz); (其中clazz是您为其定义记录器的类)。

Using it would just boil down to configuring the appenders (e.g. FileAppender) and log levels in a central file (.xml or .properties) and in each class that needs to define a logger you'd just do Log l = LogFactory.getLog(clazz); (where clazz is the class you define the logger for).

你可以制作logger public static也可以从其他类中使用它,但是我不推荐它,因为你通常想知道哪个logger(即定义了哪个类的logger)生成了一个日志条目。

You could make the logger public static and use it from other classes as well but I'd not recommend it, since you normally want to know which logger (i.e. which class that logger was defined for) generated a log entry.

这篇关于如何在Web应用程序中使用java.util.logger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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