使用多个参数进行记录 [英] Logging with multiple parameters

查看:112
本文介绍了使用多个参数进行记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个程序,其中,我必须将所有输出写入日志文件。

I am currently working on a program wherein, I must write all output to a log file.

我需要编写一个日志方法,它应该给出一个带有级别,消息,对象值,另一个消息,整数值,另一个消息和另一个消息的输出整数值,与我指定的顺序相同。我似乎无法找到执行此操作的日志方法。我正在使用 Java.util.logging 。这可能吗?

I need to write a log method, that should give an output with a level, a message, an object value, another message, an integer value, another message and another integer value, in the same order as I have specified. I can't seem to find a log method that does this. I am using Java.util.logging. Is this possible?

推荐答案

我假设您需要以下格式的日志格式
FINE,Message1,object。 GetValue(),Message2,1,Message3,2

I assume you need the log format in the below format FINE,Message1,object.GetValue(),Message2,1,Message3,2

您需要创建输出消息格式

You need to create an output message format

logger.log(Level.INFO, "{0},{1},{2},{3},{4},{5}",new Object[]{Message1,object.getValue(),Message2,1,Message3,2});

现在你需要通过扩展Formatter类来创建一个自定义格式化程序

Now you need to create a custom formatter which by extending Formatter class

public class DataFormatter extends Formatter {

@Override
public synchronized String format(LogRecord record) {
    String formattedMessage = formatMessage(record);
    String throwable = "";
    String outputFormat = "%1$s, %2$s \n %3$s"; //Also adding for logging exceptions
    if (record.getThrown() != null) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        pw.println();
        record.getThrown().printStackTrace(pw);
        pw.close();
        throwable = sw.toString();
    }
    return String.format(outputFormat,record.getLevel().getName(),formattedMessage,throwable);
}
}

现在设置新创建的格式化程序

Now set the newly created formatter

    for(int i=0;i<logger.getHandlers().length;i++)
        logger.getHandlers()[i].setFormatter(new DataFormatter());

这篇关于使用多个参数进行记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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