问题描述
我想使用Java util日志记录按照以下格式创建每个请求的日志文件.
I want to create the log file per request in the format below, using java util logging.
YYYYMMDD_HHMMSS.log
任何人都请让我知道如何使用Java util日志记录来实现这一目标?
Anybody please let me know how can I achieve this using java util logging?
推荐答案
The FileHandler doesn't support generating file names by date and time from the LogManager.
如果要在启动时生成文件名,则可以将FileHandler子类化,并创建静态方法以使用 SimpleDateFormat . LogManager 支持配置"选项,该选项还允许您安装自定义代码来设置和安装FileHandler.
If you want to generate a file name on startup you can subclass the FileHandler and create a static method to generate your file name using a SimpleDateFormat. The LogManager supports a 'config' option that will also allow you to install custom code to setup and install a FileHandler.
public class RollingFileHandler extends FileHandler {
public RollingFileHandler() throws IOException {
super(fileName(), 0, 1, true);
}
private static String fileName() {
return new SimpleDateFormat("'%h'yyyyMMdd_HHmmss").format(new Date(System.currentTimeMillis()));
}
}
如果要为每个LogRecord生成一个文件名,则必须创建一个自定义处理程序,它将在每次发布时创建并关闭FileHandler.
If you want to generate a file name per each LogRecord you have to create a custom Handler that will create and close a FileHandler on each publish.
public class DatedFileHandler extends Handler {
@Override
public synchronized void publish(LogRecord r) {
if (isLoggable(r)) {
try {
FileHandler h = new FileHandler(fileName(r), 0, 1, true);
try {
h.setLevel(getLevel());
h.setEncoding(getEncoding());
h.setFilter(getFilter());
h.setFormatter(getFormatter());
h.setErrorManager(getErrorManager());
h.publish(r);
} finally {
h.close();
}
} catch (IOException | SecurityException jm) {
this.reportError(null, jm, ErrorManager.WRITE_FAILURE);
}
}
}
@Override
public void flush() {
}
@Override
public void close() {
super.setLevel(Level.OFF);
}
private String fileName(LogRecord r) {
return new SimpleDateFormat("'%h'yyyyMMdd_HHmmss").format(new Date(r.getMillis()));
}
}
这篇关于如何使用Java util日志记录框架以特定格式为每个记录创建日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!