java.util.logging: how to suppress date line

后端 未结 3 966
日久生厌
日久生厌 2020-12-01 23:40

I\'m trying to suppress output of the date line durinng logging when using the default logger in java.util.logging. For example, here is a typical output:

Jun 1,         


        
3条回答
  •  难免孤独
    2020-12-02 00:01

    Write a custom formatter extending java.util.logging.Formatter class and implement the String format(LogRecord) method according to your needs. For example, the following formatter shows only the log message (and the throwable stacktrace if an exception is being logged):

    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.util.logging.Formatter;
    import java.util.logging.LogRecord;
    
    class CustomRecordFormatter extends Formatter {
        @Override
        public String format(final LogRecord r) {
            StringBuilder sb = new StringBuilder();
            sb.append(formatMessage(r)).append(System.getProperty("line.separator"));
            if (null != r.getThrown()) {
                sb.append("Throwable occurred: "); //$NON-NLS-1$
                Throwable t = r.getThrown();
                PrintWriter pw = null;
                try {
                    StringWriter sw = new StringWriter();
                    pw = new PrintWriter(sw);
                    t.printStackTrace(pw);
                    sb.append(sw.toString());
                } finally {
                    if (pw != null) {
                        try {
                            pw.close();
                        } catch (Exception e) {
                            // ignore
                        }
                    }
                }
            }
            return sb.toString();
        }
    }
    

    This is how you use it:

    import java.util.logging.ConsoleHandler;
    import java.util.logging.Logger;
    
    class A {
        private static final Logger LOGGER = Logger.getLogger(A.class.getName());
    
        static {
            CustomRecordFormatter formatter = new CustomRecordFormatter();
            ConsoleHandler consoleHandler = new ConsoleHandler();
            consoleHandler.setFormatter(formatter);
            LOGGER.addHandler(consoleHandler);
        }
    
        public void doSomething() {
            LOGGER.info("something happened");
        }
    }
    

提交回复
热议问题