在 java 日志格式器中使用简单的 class 名称

Using simple class name in java logging formatter

我有一个 SimpleFormatter 用于使用字符串
登录我的应用程序 "%1$tF %1$tT %4$-7s %2$s %5$s%6$s%n"

我想使用简单的 class 名称而不是规范名称。是否有可用于 2$ 字段的格式选项?或者这是否需要编写一个新的处理程序?

例如,而不是
2019-02-06 07:09:09 INFO simplex.tools.SIMPLEXScheduler main Start

我想看
2019-02-06 07:09:09 INFO SIMPLEXScheduler main Start

Is there a format option I can use with the 2$ field?

SimpleFormatter only supports the functionality in the java.util.Formatter。目前无法将 class 名称格式化为简单的 class 名称。

Or does this require writing a new Handler?

一个选择是写一个新的 java.util.logging.Formatter. There are some hacks that you can do by just installing a java.util.logging.Filter to change the class name but you should avoid doing that. Use logp instead as suggested by P.J.Meisch

免责声明:我是 com.sun.mail.util.logging package included with the JavaMail 项目的内容开发人员。

如果您有权访问 JavaMail,则可以使用 com.sun.mail.util.logging.CompactFormatter which will only print the simple class name. The trade off is that it will print compact stack traces 作为例外。参数 1 到 6 与 SimpleFormatter 的顺序相同,因此可以使用相同的模式。

如果您不想包含 JavaMail,则可以改用 com.sun.mail:logging-mailhandler 工件。

我按照 jmehrens 的建议编写了自定义格式化程序。如果我需要更复杂的东西,我可能会尝试转移到另一个框架,比如 log4j,但这就是我现在想要的。谢谢指教!

                Formatter formatter = new Formatter() {
                    @Override
                    public String format(LogRecord record) {
                        String source = "";
                        if (record.getSourceClassName() != null) {
                            try {
                                source = Class.forName(record.getSourceClassName()).getSimpleName();
                            } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                            }
                            if (record.getSourceMethodName() != null) {
                                source += " " + record.getSourceMethodName();
                            }
                        } else {
                            source = record.getLoggerName();
                        }
                        String message = formatMessage(record);
                        String throwable = "";
                        if (record.getThrown() != null) {
                            StringWriter sw = new StringWriter();
                            PrintWriter pw = new PrintWriter(sw);
                            pw.println();
                            record.getThrown().printStackTrace(pw);
                            pw.close();
                            throwable = sw.toString();
                        }
                        return String.format(getLogFormat(), new Date(record.getMillis()), source,
                                record.getLoggerName(), record.getLevel(), message, throwable);
                    }

                };