java logging 格式化,如何使用java.util.logging对齐日志消息

本文介绍如何使用Java Util Logging自定义Formatter,通过` `实现日志信息的字段对齐,包括时间、线程ID、方法名等。提供了一个实例代码,并探讨了如何根据字段长度动态调整制表符数量。编辑版建议使用`String.format()`进行更清晰的代码组织。
摘要由CSDN通过智能技术生成

Can someone post how to achieve alignment in log messages:

[10:14:31 main package1.Class1 INFO]: initializing data..

[10:14:31 Thread-0 package2.Class2 method1 INFO]: log message

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.

Thanks

解决方案

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();

}

}

You get the idea.

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.

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

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.

EDIT:

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)

));

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值