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

Obe*_*ane 117 java logging

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

Oct 12, 2008 9:45:18 AM myClassInfoHere
INFO: MyLogMessageHere
Run Code Online (Sandbox Code Playgroud)

我怎么做到这一点?

Oct 12, 2008 9:45:18 AM myClassInfoHere - INFO: MyLogMessageHere
Run Code Online (Sandbox Code Playgroud)

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

Tre*_*son 79

从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'
Run Code Online (Sandbox Code Playgroud)

或者,您也可以将此添加到您的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'
Run Code Online (Sandbox Code Playgroud)

  • 在我将其更改为使用双引号后,它在Eclipse中工作. (5认同)
  • 从Java7开始.Java6文档中没有提到这一点. (4认同)

Ond*_*žka 72

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

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

-Djava.util.logging.SimpleFormatter.format=... 
Run Code Online (Sandbox Code Playgroud)

看到这里.

我最喜欢的是:

-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
Run Code Online (Sandbox Code Playgroud)

这使输出像:

2014-09-02 16:44:57 SEVERE org.jboss.windup.util.ZipUtil unzip: Failed to load: foo.zip
Run Code Online (Sandbox Code Playgroud)

2)将它放到IDE中

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

3)把它放到Maven - 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>
Run Code Online (Sandbox Code Playgroud)

4)手工制作

我有一个几乎没有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();
  }
}
Run Code Online (Sandbox Code Playgroud)


Guy*_*y L 46

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

请注意,这需要在创建第一个SimpleFormatter之前设置 - 正如在注释中所写的那样.

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

  • 请注意,这需要在创建第一个SimpleFormatter之前设置 - 例如在获取全局记录器的处理程序之前. (5认同)
  • 这是强制日志写入单行而不向JVM添加任何其他启动参数的最快方法.但请确保在代码中调用"new SimpleFormatter()"之前设置此属性. (3认同)

Ben*_*ers 35

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

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

  • 小心创建一个新Date对象!你应该确保代表日期LogRecord.Date使用默认构造函数创建new 时,它将表示Formatter进程的日期和时间LogRecord,而不是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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Jin*_*won 10

这就是我正在使用的.

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

你会得到类似......

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!!!
Run Code Online (Sandbox Code Playgroud)


rup*_*web 7

Eclipse配置

每个截图,在Eclipse中选择"运行方式",然后选择"运行配置...",并使用双引号而不是引号添加Trevor Robinson的答案.如果你错过双引号,你会得到"无法找到或加载主类"的错误.

  • 根据之前的回答,这适用于Java 7. Java 6没有此功能. (2认同)

Obe*_*ane 5

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

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

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


Lei*_*ell -3

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

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

  • 这不是一些随机记录器应用程序。这是java自己的`java.util.logging.Logger` (3认同)