3

我正在使用 java.util.logging,它适用于高于 FINE 的更高级别,但不适用于较低级别,尽管我已将级别设置为 FINEST。我也试过给它 Level.ALL。我有如下用户定义的类。

public class Tracer extends Logger {
    public Tracer(String name) {
        super(name, null);
        addFileHandler();
        addConsoleHandler();
    }

    private void addConsoleHandler() {
        SSFormatter ssFormatter = new SSFormatter();
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(ssFormatter);
        consoleHandler.setLevel(Level.FINEST);
        this.addHandler(consoleHandler);
    }

    private void addFileHandler() {
        try {
            FileHandler fileHandler = new FileHandler("log.txt", false);
            fileHandler.setFormatter(new SSFormatter());
            fileHandler.setLevel(Level.FINEST);
            this.addHandler(fileHandler);
        } catch (SecurityException e) {
            e.printStackTrace();
            this.warning("SecurityException occurred while adding FileHandler");
        } catch (IOException e) {
            e.printStackTrace();
            this.warning("IOException occurred while adding FileHandler");
        }
    }

    private class SSFormatter extends Formatter {

        @Override
        public String format(LogRecord paramLogRecord) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(paramLogRecord.getLoggerName()).append("|")
                    .append(paramLogRecord.getSourceClassName()).append("|")
                    .append(paramLogRecord.getSourceMethodName()).append(":::")
                    .append(paramLogRecord.getMessage()).append("\n");
            return stringBuilder.toString();
        }
    }
    public static void main(String[] args) {
        Tracer tracer = new Tracer("ss.tracer");
        tracer.info("This is to test my tracer");
        tracer.warning("This is warning from my tracer");
        tracer.severe("This is severe from my tracer");
        tracer.fine("this is fine");
        tracer.finer("this is finer");
        tracer.finest("this is finest");
    }
}

当我运行 main 方法时,我得到控制台和文件输出如下

ss.tracer|screen.seizer.trace.Tracer|main:::This is to test my tracer
ss.tracer|screen.seizer.trace.Tracer|main:::This is warning from my tracer
ss.tracer|screen.seizer.trace.Tracer|main:::This is severe from my tracer

谢谢,希望我已经清楚地提出了我的问题。

4

2 回答 2

4

我正在使用 java.util.logging,它适用于高于 FINE 的更高级别,但不适用于较低级别,尽管我已将级别设置为 FINEST。

处理程序具有级别,但Logger也具有默认为 的级别INFO。这是Logger构造函数的行:

levelValue = Level.INFO.intValue();

即使处理程序中的级别低于INFO,如果记录器级别更高,那么这些日志消息都不会到达处理程序。在每种fine方法和其他方法中,都有如下检查:

if (Level.FINE.intValue() < levelValue) {
    return;
}

如果您在您的中调用类似以下内容,main则将打印所有级别消息。

tracer.setLevel(Level.ALL);
于 2011-12-31T19:28:15.707 回答
1

您需要在记录器中的处理程序和记录器本身上设置日志级别。日志记录仅在两个级别中的“最粗略”执行。这是一个完成这项工作的日志记录类。

import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

public class Log {

    private static final Logger logger = Logger.getGlobal();

    private static Level logLevel = Level.INFO;
    static {
        // Remove all the default handlers (usually just one console handler)
        Logger rootLogger = Logger.getLogger("");
        Handler[] rootHandlers = rootLogger.getHandlers();
        for (Handler handler : rootHandlers) {
            rootLogger.removeHandler(handler);
        }

        // Add our own handler
        ConsoleHandler handler = new ConsoleHandler();
        handler.setLevel(logLevel);
        handler.setFormatter(new LogFormatter());
        logger.addHandler(handler);
        logger.setLevel(logLevel);
    }

    public static class LogFormatter extends Formatter {
        @Override
        public String format(L    ogRecord record) {
            String stackTrace = "";
            Throwable thrown = record.getThrown();
            if (thrown != null) {
                StringWriter stacktraceWriter = new StringWriter();
                try (PrintWriter writer = new PrintWriter(stacktraceWriter)) {
                    thrown.printStackTrace(writer);
                }
                stackTrace = stacktraceWriter.toString();
            }
            return ZonedDateTime.ofInstant(Instant.ofEpochMilli(record.getMillis()), ZoneId.of("UTC")).format(DateTimeFormatter.ISO_ZONED_DATE_TIME) + "\t" + record.getLevel()
                    + "\t" + record.getMessage() + "\n" + stackTrace;
        }
    }

    private static final String classname = Log.class.getName();

    private static String callerRef() {
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        if (stackTraceElements.length < 4) {
            return "";
        } else {
            int i = 1;
            for (; i < stackTraceElements.length; i++) {
                if (stackTraceElements[i].getClassName().equals(classname)) {
                    break;
                }
            }
            for (; i < stackTraceElements.length; i++) {
                if (!stackTraceElements[i].getClassName().equals(classname)) {
                    break;
                }
            }
            if (i < stackTraceElements.length) {
                return stackTraceElements[i].toString();
            } else {
                return "[in unknown method]";
            }
        }
    }

    public static void setLogLevel(Level newLogLevel) {
        logLevel = newLogLevel;
        for (Handler handler : logger.getHandlers()) {
            handler.setLevel(newLogLevel);
        }
        Log.logger.setLevel(newLogLevel);
    }

    public static int getLevelNum() {
        return logLevel.intValue();
    }

    public static int getLevelNum(Level level) {
        return level.intValue();
    }

    public static void fine(String msg) {
        logger.log(Level.FINE, msg);
    }

    public static void info(String msg) {
        logger.log(Level.INFO, msg);
    }

    public static void warning(String msg) {
        logger.log(Level.WARNING, msg + "\t " + callerRef());
    }

    public static void error(String msg) {
        logger.log(Level.SEVERE, msg + "\t " + callerRef());
    }

    public static void exception(String msg, Throwable cause) {
        logger.log(Level.SEVERE, msg + "\t " + callerRef(), cause);
    }

}
于 2014-09-01T08:08:55.297 回答