如何让 java 日志输出显示在一行上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/194765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:10:15  来源:igfitidea点击:

How do I get java logging output to appear on a single line?

javalogging

提问by Obediah Stane

At the moment a default entry looks something like this:

目前,默认条目如下所示:

Oct 12, 2008 9:45:18 AM myClassInfoHere
INFO: MyLogMessageHere

How do I get it to do this?

我如何让它做到这一点?

Oct 12, 2008 9:45:18 AM myClassInfoHere - INFO: MyLogMessageHere

Clarification I'm using java.util.logging

澄清我正在使用 java.util.logging

回答by Leigh Caldwell

This logging is specific to your application and not a general Java feature. What application(s) are you running?

此日志记录特定于您的应用程序,而不是通用的 Java 功能。您正在运行什么应用程序?

It might be that this is coming from a specific logging library that you are using within your own code. If so, please post the details of which one you are using.

这可能来自您在自己的代码中使用的特定日志记录库。如果是这样,请发布您正在使用的详细信息。

回答by anjanb

if you're using java.util.logging, then there is a configuration file that is doing this to log contents (unless you're using programmatic configuration). So, your options are
1) run post -processor that removes the line breaks
2) change the log configuration AND remove the line breaks from it. Restart your application (server) and you should be good.

如果您使用的是 java.util.logging,则有一个配置文件正在执行此操作以记录内容(除非您使用的是编程配置)。因此,您的选择是
1) 运行删除换行符的后处理器
2) 更改日志配置并从中删除换行符。重新启动您的应用程序(服务器),您应该会很好。

回答by Obediah Stane

I've figured out a way that works. You can subclass SimpleFormatter and override the format method

我想出了一个有效的方法。您可以继承 SimpleFormatter 并覆盖 format 方法

    public String format(LogRecord record) {
        return new java.util.Date() + " " + record.getLevel() + " " + record.getMessage() + "\r\n";
    }

A bit surprised at this API I would have thought that more functionality/flexibility would have been provided out of the box

对这个 API 有点惊讶,我原以为会提供更多的功能/灵活性

回答by Benno Richters

Like Obediah Stane said, it's necessary to create your own formatmethod. But I would change a few things:

正如 Obediah Stane 所说,有必要创建自己的format方法。但我会改变一些事情:

  • Create a subclass directly derived from Formatter, not from SimpleFormatter. The SimpleFormatterhas nothing to add anymore.

  • Be careful with creating a new Dateobject! You should make sure to represent the date of the LogRecord. When creating a new Datewith the default constructor, it will represent the date and time the Formatterprocesses the LogRecord, not the date that the LogRecordwas created.

  • 创建一个直接从 派生的子类Formatter,而不是从派生SimpleFormatter。该SimpleFormatter有什么可再补充。

  • 创建新Date对象时要小心!您应该确保代表LogRecord. 当创建一个新的Date默认构造,其所代表的日期和时间Formatter过程LogRecord的,不是日期LogRecord的创建。

The following class can be used as formatterin a Handler, which in turn can be addedto the Logger. Note that it ignores all class and method information available in the LogRecord.

下面的类可以被用作格式化器中一个Handler,这反过来又可以加入Logger。请注意,它会忽略LogRecord.

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

public final class LogFormatter extends Formatter {

    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

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

        sb.append(new Date(record.getMillis()))
            .append(" ")
            .append(record.getLevel().getLocalizedName())
            .append(": ")
            .append(formatMessage(record))
            .append(LINE_SEPARATOR);

        if (record.getThrown() != null) {
            try {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                record.getThrown().printStackTrace(pw);
                pw.close();
                sb.append(sw.toString());
            } catch (Exception ex) {
                // ignore
            }
        }

        return sb.toString();
    }
}

回答by Ondra ?i?ka

1) -Djava.util.logging.SimpleFormatter.format

1) -Djava.util.logging.SimpleFormatter.format

Java 7 supports a property with the java.util.Formatterformat string syntax.

Java 7 支持具有java.util.Formatter格式字符串语法的属性。

-Djava.util.logging.SimpleFormatter.format=... 

See here.

这里

My favorite is:

我最喜欢的是:

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

which makes output like:

这使得输出如下:

2014-09-02 16:44:57 SEVERE org.jboss.windup.util.ZipUtil unzip: Failed to load: foo.zip

2) Putting it to IDEs

2) 将其放入 IDE

IDEs typically let you set system properties for a project. E.g. in NetBeans, instead of adding -D...=... somewhere, add the property in the action dialog, in a form of java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-...- without any quotes. The IDE should figure out.

IDE 通常允许您为项目设置系统属性。例如,在 NetBeans 中,不是在某处添加 -D...=...,而是在操作对话框中以java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-...-的形式添加属性,不带任何引号。IDE 应该会弄清楚。

3) Putting that to Maven - Surefire

3) 把它放到 Maven - Surefire

For your convenience, Here is how to put it to Surefire:

为方便起见,以下是将其放入 Surefire 的方法:

        <!-- Surefire -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.17</version>
            <configuration>
                <systemPropertyVariables>
                    <!-- Set JUL Formatting -->
                    <java.util.logging.SimpleFormatter.format>%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n</java.util.logging.SimpleFormatter.format>
                </systemPropertyVariables>
            </configuration>
        </plugin>

4) Hand-made

4) 手工制作

I have a library with few java.util.loggingrelated classes. Amongst them, it's SingleLineFormatter. Downloadable jar here.

我有一个几乎没有java.util.logging相关类的库。其中,是SingleLineFormatter。可在此处下载 jar 。

public class SingleLineFormatter extends Formatter {

  Date dat = new Date();
  private final static String format = "{0,date} {0,time}";
  private MessageFormat formatter;
  private Object args[] = new Object[1];

  // Line separator string.  This is the value of the line.separator
  // property at the moment that the SimpleFormatter was created.
  //private String lineSeparator = (String) java.security.AccessController.doPrivileged(
  //        new sun.security.action.GetPropertyAction("line.separator"));
  private String lineSeparator = "\n";

  /**
   * Format the given LogRecord.
   * @param record the log record to be formatted.
   * @return a formatted log record
   */
  public synchronized String format(LogRecord record) {

    StringBuilder sb = new StringBuilder();

    // Minimize memory allocations here.
    dat.setTime(record.getMillis());    
    args[0] = dat;


    // Date and time 
    StringBuffer text = new StringBuffer();
    if (formatter == null) {
      formatter = new MessageFormat(format);
    }
    formatter.format(args, text, null);
    sb.append(text);
    sb.append(" ");


    // Class name 
    if (record.getSourceClassName() != null) {
      sb.append(record.getSourceClassName());
    } else {
      sb.append(record.getLoggerName());
    }

    // Method name 
    if (record.getSourceMethodName() != null) {
      sb.append(" ");
      sb.append(record.getSourceMethodName());
    }
    sb.append(" - "); // lineSeparator



    String message = formatMessage(record);

    // Level
    sb.append(record.getLevel().getLocalizedName());
    sb.append(": ");

    // Indent - the more serious, the more indented.
    //sb.append( String.format("% ""s") );
    int iOffset = (1000 - record.getLevel().intValue()) / 100;
    for( int i = 0; i < iOffset;  i++ ){
      sb.append(" ");
    }


    sb.append(message);
    sb.append(lineSeparator);
    if (record.getThrown() != null) {
      try {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        record.getThrown().printStackTrace(pw);
        pw.close();
        sb.append(sw.toString());
      } catch (Exception ex) {
      }
    }
    return sb.toString();
  }
}

回答by Trevor Robinson

As of Java 7, java.util.logging.SimpleFormattersupports getting its formatfrom a system property, so adding something like this to the JVM command line will cause it to print on one line:

从 Java 7 开始,java.util.logging.SimpleFormatter支持从系统属性获取其格式,因此将类似这样的内容添加到 JVM 命令行将使其打印在一行上:

-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'

Alternatively, you can also add this to your logger.properties:

或者,您也可以将其添加到您的logger.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'

回答by rupweb

Eclipse config

日食配置

Per screenshot, in Eclipse select "run as" then "Run Configurations..." and add the answer from Trevor Robinson with double quotes instead of quotes. If you miss the double quotes you'll get "could not find or load main class" errors.

根据屏幕截图,在 Eclipse 中选择“运行方式”,然后选择“运行配置...”,并使用双引号而不是引号添加来自 Trevor Robinson 的答案。如果您错过了双引号,您将收到“无法找到或加载主类”错误。

回答by Guy L

Similar to Tervor, But I like to change the property on runtime.

类似于 Tervor,但我喜欢在运行时更改属性。

Note that this need to be set before the first SimpleFormatter is created - as was written in the comments.

请注意,这需要在创建第一个 SimpleFormatter 之前设置 - 如注释中所述。

    System.setProperty("java.util.logging.SimpleFormatter.format", 
            "%1$tF %1$tT %4$s %2$s %5$s%6$s%n");

回答by Jin Kwon

This is what I'm using.

这就是我正在使用的。

public class VerySimpleFormatter extends Formatter {

    private static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    @Override
    public String format(final LogRecord record) {
        return String.format(
                "%1$s %2$-7s %3$s\n",
                new SimpleDateFormat(PATTERN).format(
                        new Date(record.getMillis())),
                record.getLevel().getName(), formatMessage(record));
    }
}

You'll get something like...

你会得到类似...

2016-08-19T17:43:14.295+09:00 INFO    Hey~
2016-08-19T17:43:16.068+09:00 SEVERE  Seriously?
2016-08-19T17:43:16.068+09:00 WARNING I'm warning you!!!

回答by Mohammad Irfan

If you log in a web application using tomcat add:

如果您使用 tomcat 登录 Web 应用程序,请添加:

-Djava.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter

On VM arguments

关于 VM 参数