java创建log文件,Java Logger:以后缀号+ .log创建文件

本文介绍了如何使用Java的java.util.logging包中的FileHandler来定制日志文件的名称和旋转策略。通过设置文件路径模式,利用%g组件动态替换为日志生成的编号,实现日志文件如'.0.log','.1.log'等格式。同时展示了自定义日志格式的方法,根据日志级别添加不同的前缀。
摘要由CSDN通过智能技术生成

I am using the Java Logger in the java.util.logging package. This is how I create the logger currently:

FileHandler fileHandler = new FileHandler(filePath, 5242880, 5, true);

fileHandler.setFormatter(new java.util.logging.Formatter() {

@Override

public String format(LogRecord logRecord) {

if(logRecord.getLevel() == Level.INFO) {

return "[INFO " + createDateTimeLog() + "] " + logRecord.getMessage() + "\r\n";

} else if(logRecord.getLevel() == Level.WARNING) {

return "[WARN " + createDateTimeLog() + "] " + logRecord.getMessage() + "\r\n";

} else if(logRecord.getLevel() == Level.SEVERE) {

return "[ERROR " + createDateTimeLog() + "] " + logRecord.getMessage() + "\r\n";

} else {

return "[OTHER " + createDateTimeLog() + "] " + logRecord.getMessage() + "\r\n";

}

}

});

logger.addHandler(fileHandler)

Now when my logger logs, it creates a file with the extention .0,.1,.2 (etc). I would prefer for it to say .0.log, .1.log (etc). I cannot find where I can set this. Any ideas / help would be great.

解决方案

When you construct your fileHandler object, modify filePath to use a pattern. Create a pattern that makes use of the %g component. This component will be replaced at runtime with the generation number to distinguish rotated logs.

Example

To place log file in the system temp directory with form %TEMP%/mylog.1.log, use the following pattern:

`"%t/mylog.%g.log"`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值