有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

此时,默认条目如下所示:

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

我如何让它这样做

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

我正在使用java。util。伐木


共 (6) 个答案

  1. # 1 楼答案

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

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

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

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

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

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

    here

    我最喜欢的是:

    -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
    

    这使得输出像:

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

    2) 把它放到IDEs上

    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>
    

    4) 手工制作

    我有一个带few ^{} related classes的图书馆。其中SingleLineFormatter。 可下载jarhere

    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();
      }
    }
    
  3. # 3 楼答案

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

    • 创建直接从Formatter派生的子类,而不是从SimpleFormatter派生的子类。{}再也没有什么可添加的了

    • 创建新的Date对象时要小心!您应该确保表示LogRecord的日期。使用默认构造函数创建新的Date时,它将表示Formatter处理LogRecord的日期和时间,而不是创建LogRecord的日期

    下面的类可以是Handler中的used as formatter,而这个类又可以是addedLogger。注意,它忽略了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();
        }
    }
    
  4. # 4 楼答案

    这就是我用的

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

    你会得到像

    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!!!
    
  5. # 5 楼答案

    从Java 7开始,java.util.logging.SimpleFormatter支持从系统属性获取其format,因此向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'
    

    或者,您也可以将其添加到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'
    
  6. # 6 楼答案

    Eclipse config

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