栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用简单格式化程序修改日志格式?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用简单格式化程序修改日志格式?

一堆东​​西可能在这里出错。首先,请确保您正在运行的Java版本(7
b138)已修复了JDK-6381464的问题:SimpleFormatter应该使用一种单行格式。

文档中未解释的一件事是,仅当您通过命令行设置模式且模式包含空格字符时,才需要在模式上加引号。

因此,如果要在logging.properties中设置格式,则请删除引号:

java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n

如果要将格式设置为系统属性,则必须在启动时进行设置:

-Djava.util.logging.SimpleFormatter.format="%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n"

接下来要做的是使用测试程序来验证您的模式是否已编译。如果模式语法错误,则SimpleFormatter将退回到默认模式。这是一个示例测试程序:

public static void main(String[] args) throws Exception {    final String format = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n";    final String key = "java.util.logging.SimpleFormatter.format";    test(format);    test(System.getProperty(key, format));    test(LogManager.getLogManager().getProperty(key));    test(new SimpleFormatter());}private static void test(Formatter f) {    LogRecord record = newLogRecord();    System.out.println(f.format(record));}private static LogRecord newLogRecord() {    LogRecord r = new LogRecord(Level.INFO, "Message");    r.setSourceClassName("sourceClassName");    r.setSourceMethodName("sourceMethodName");    r.setLoggerName("loggerName");    return r;}private static void test(String format) {    if (format != null) {        LogRecord record = newLogRecord();        Throwable t = record.getThrown();        System.out.println(String.format(format,     new java.util.Date(record.getMillis()),     record.getSourceClassName(),     record.getLoggerName(),     record.getLevel().getLocalizedName(),     record.getMessage(),     t != null ? t.toString() : ""));        //TODO: Place printStackTrace into a string.    } else {        System.out.println("Format is null.");    }}

最后,该格式只能在启动时设置一次。加载SimpleFormatter后,该模式将在类的整个生命周期中使用。

System.setProperty
仅当您在开始记录之前设置了模式时,使用才会起作用,因此,不要依赖于在复杂程序中使用的路由。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/508071.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号