如何使用java.util.logging对齐日志消息 [英] How to align log messages using java.util.logging

查看:400
本文介绍了如何使用java.util.logging对齐日志消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以在日志消息中发布如何实现对齐:

Can someone post how to achieve alignment in log messages:

[10:14:31 main     package1.Class1 <init>  INFO]: initializing data..
[10:14:31 Thread-0 package2.Class2 method1 INFO]: log message

我知道我可以使用log4j,但是我想知道如何使用JUL来实现这一点. 我尝试使用MessageFormat,FieldPosition,但无济于事.

I know I can use log4j but I want to know how to achieve this with JUL. I tried using MessageFormat, FieldPosition but to no avail.

谢谢

推荐答案

您可以创建自己的java.util.logging.Formatter.为此,您可以这样扩展它:

You can create you own java.util.logging.Formatter. For that you can extend it this way:

import java.util.logging.Formatter;
import java.util.logging.LogRecord;

public final class MyFormatter extends Formatter {

    @Override
    public String format(LogRecord record) {
        StringBuilder sb = new StringBuilder();

        // Build output the way you want
        sb.append(new Date(record.getMillis()))
            .append(" \t")
            .append(record.getThreadID())
            .append(" \t")
            .append(record.getSourceMethodName())
            .append(" \t")
            .append(record.getSourceClassName())
            .append(" \t")
            .append(record.getLevel().getLocalizedName())
            .append(": ")
            .append(formatMessage(record))
            .append(System.getProperty("line.separator"));

        return sb.toString();
    }
}

您明白了.

这只是如何使用\ t处理输出并对齐输出的示例.这不是一个完美的解决方案,因为您事先不知道SourceMethodName或SourceClassName或任何其他输出字段的长度,并且仅一个\ t可能不足以完全对齐它们.

This is just an example of how you can handle the output and align it using \t. This is not a perfect solution because you don't know beforehand what's the length of SourceMethodName or SourceClassName or any other output field and only one \t may not be enough to align them all, perfectly.

该解决方案可能会根据需要使用\ t来涵盖几乎所有您能想到的情况.

The solution may be in use as many \t as necessary to cover almost all situations you can think of.

话虽如此,理想的解决方案是保存所有输出信息,最后根据每个字段的长度计算要使用多少\ t.

That being said, the perfect solution is to save all output infos and, at the end, calculate how many \t to use depending on the lenght of each field.

您可以将StringBuilderString.format()结合使用,而不是\ t,从而使代码更简洁,更易于阅读:

Instead of \t you can use StringBuilder together with String.format() to a cleaner and easier to read code:

sb.append(String.Format("[%1$-10s %2$-10s %3$-10s]: %4",
    new Data(record.getMillis(),
    record.getSourceMethodName(),
    record.getSourceClassName(),
    formatMessage(record)
));

检查此页面有关如何使用String.format()将字符串格式化为桌子.

Check this page on how to use String.format() to format string into tables.

这篇关于如何使用java.util.logging对齐日志消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆