问题描述
我正在使用 java.util.logging
进行日志记录(我不想使用log4j或其他任何内容)。
I am using java.util.logging
for logging (I don't want to use log4j or anything else).
这是我完整的私有logging.properties:
This is my complete private logging.properties:
handlers= java.util.logging.FileHandler
.level= INFO
java.util.logging.FileHandler.pattern = my.log
java.util.logging.FileHandler.limit = 500000
java.util.logging.FileHandler.count = 40
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
这是我程序中的代码:
public static Logger log = Logger.getLogger(MyClass.class.getName());
// Is there anything else to be init'ed here?
// I don't. I just start using log directly in the code.
log.severe("something");
log.info("something else");
因为这会给每行两条日志消息,所以我试过这个
Since this gives each log message on 2 lines, I tried this
在第一个回复中复制LogFormatter类。
Copied the LogFormatter class in the first reply exactly.
在我的logging.properties中更改了一行
Changed one line in my logging.properties
java.util.logging.FileHandler.formatter = com.mycomp.myproj.LogFormatter;
现在我的日志已经开始以XML格式显示。我强烈认为 FileHandler
不喜欢我的 com.mycomp.myproj.LogFormatter
,因此默认为默认 XMLFormatter
。我怎么弄清楚为什么 FileHandler
没有使用我的LogFormatter类?
Now my log has started appearing in XML. I have a strong feeling that the FileHandler
doesn't like my com.mycomp.myproj.LogFormatter
and hence defaulting to the default XMLFormatter
. How do I figure out why FileHandler
isn't using my LogFormatter class?
推荐答案
您可以在FileHandler实例上的代码本身中设置格式化程序。
You can set the formatter in the code itself on the FileHandler instance.
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
// please change name of your own choice
Logger log = Logger.getLogger("CustomLogger");
log.setUseParentHandlers(false);
log.setLevel(Level.ALL);
FileHandler handler = new FileHandler("[log_file_location]");
handler.setFormatter(new CustomFormatter()); // set formatter
log.addHandler(handler);
log.info("test message");
handler.close(); // close the handler at some later point in your application.
CustomFormatter类定义如下。
The CustomFormatter class is defined as follows.
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public class CustomFormatter extends Formatter {
@Override
public String format(LogRecord record) {
StringBuffer buffer = new StringBuffer();
buffer.append(record.getMessage());
return buffer.toString();
}
}
您可以在CustomFormatter中编码输出您想要的任何格式的邮件。希望这会有所帮助。
You can code in CustomFormatter to output the messages in any format you want. Hope this helps.
这篇关于子类化java.util.logging.Formatter不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!