首页 > 解决方案 > 如何在打印日志时始终避免打印记录器主类名称?

问题描述

我想打印登录控制台。我正在使用java.util.logging.Logger类来打印日志。下面是我的代码。

import java.text.MessageFormat;
import java.util.logging.Logger;
import com.practice.exception.InvalidOperationException;

public final class Log {

    private static Logger logger = Logger.getLogger(Log.class.getSimpleName());
    private Log() {
        throw new InvalidOperationException("Object creation is not allowed.");
    }
    public static void logInfo(String pattern, Object...arguments) {
        MessageFormat format = new MessageFormat(pattern);
        String message = format.format(arguments);
        logger.info(message);
    }
}

我正在使用 Log.logInfo() 方法打印日志。我的问题是当我打印日志时,它总是以以下格式打印。每次打印一些日志时,我都不想打印 “Apr 20, 2019 1:06:14 PM com.practice.utils.Log logInfo” 。我们有什么办法可以做到这一点?

Apr 20, 2019 1:06:14 PM com.practice.utils.Log logInfo
INFO: First text I have entered.
Apr 20, 2019 1:06:14 PM com.practice.utils.Log logInfo
INFO: Second text I have entered.

标签: javalogging

解决方案


在此处查看一些建议: https ://www.logicbig.com/tutorials/core-java-tutorial/logging/customizing-default-format.html

最简单的是(来自链接):

System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] [%4$-7s] %5$s %n");

甚至更简单(仅打印日志级别和消息):

System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s: %5$s %n");

推荐阅读