日志记录不适用于较低级别

发布于 2024-12-23 12:12:37 字数 2429 浏览 1 评论 0原文

我正在使用 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

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

I am using java.util.logging, which works fine for higher levels above FINE but doesn't work for lower levels, though I have set level as FINEST. I have tried giving it Level.ALL also. I have user defined class as follows.

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

When I run main method, I get the console and file output as follows

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

Thanks, Hope I have put forward my question clear.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

無心 2024-12-30 12:12:37

我正在使用 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);

I am using java.util.logging, which works fine for higher levels above FINE but doesn't work for lower levels, though I have set level as FINEST.

The handlers have levels but the Logger also has a level which defaults to INFO. Here's the line from the Logger constructor:

levelValue = Level.INFO.intValue();

Even if the level in the handlers is lower than INFO, if the logger level is higher then none of those log messages will make it to the handlers. In each of the fine and other methods there are checks like:

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

If you call something like the following in your main then all of the level messages will be printed.

tracer.setLevel(Level.ALL);
终难遇 2024-12-30 12:12:37

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

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

}

You need to set the log level on both the handlers in the logger, and the logger itself. Logging is only performed at the "coarsest" of the two levels. Here is a logging class that does the job.

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

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文