如何在 Web 应用程序中使用 java.util.logger?
我正在尝试在网络应用程序中使用记录器。我添加了 FileHandler 将日志写入文件。现在,我需要在项目中的其他类/servlet 中使用相同的处理程序,以便将所有类的日志写入同一文本文件。 我怎样才能实现这个目标?
/***
* 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();
}
}
我是否需要像上面的代码一样初始化记录器并在每个类中添加处理程序?还有其他技术吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
然后
我们必须在其中一个包中维护一个 log4j.properties 文件,该文件应如下所示,
log4j.properties
}
then we have to maintain a log4j.properties file in one of our packages,and the file should be as follows,
log4j.properties
我会考虑使用 Log4J 等日志记录框架。
使用它只需在中央文件(.xml 或 .properties)中配置附加程序(例如 FileAppender)和日志级别,并且在每个需要定义记录器的类中,您只需执行
Log l = LogFactory .getLog(clazz);
(其中 clazz 是您为其定义记录器的类)。您可以将记录器设置为公共静态并从其他类中使用它,但我不推荐它,因为您通常想知道哪个记录器(即为哪个类定义了记录器)生成了日志条目。
I'd consider using a logging framework such as Log4J.
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).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.
您可以使用logging.properties 文件为整个应用程序全局定义处理程序。在此文件中,您可以微调您的日志记录需求。
请查看此处或者只是google 用于 logging.properties。
上面链接中的示例:
您甚至可以通过将 logging.properties 放置在 Web 应用程序的 WEB-INF/classes 中,为每个 Web 应用程序设置不同的日志记录行为。
You could use the logging.properties file to define your handlers globally for the whole application. In this file you can fine-tune your logging needs.
Look here or just google for logging.properties.
Example from the link above:
You can even setup different logging behavior for each of you web applications by placing the logging.properties in WEB-INF/classes of your web app.