【发布时间】:2021-09-10 08:45:38
【问题描述】:
给定一个日志工具类,如何通过该类记录所有内容,而不是为每个类创建一个Logger 对象?
例如,而不是:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Main {
private static final Logger LOG = LogManager.getLogger(Main.class);
public static void main(String[] args) {
LOG.info("Application started!");
}
}
我想做这样的事情:
import my.utils.LogUtils;
public class Main {
public static void main(String[] args) {
LogUtils.info("Application started!");
}
}
我的LogUtils 类如下所示:
package my.utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashMap;
import java.util.Map;
public final class LogUtils {
private LogUtils() {
throw new AssertionError("private constructor: " + LogUtils.class.getName());
}
private static final Map<Class<?>, Logger> LOGGERS = new HashMap<>();
static {
Class<?> current = LogUtils.class;
LOGGERS.put(current, LogManager.getLogger(current));
}
public static void info(Object msg) {
Logger logger = getFor(getCallerClass());
// logger.info()... Here's where I am stuck! What I want to log in the stack trace is the *caller* of the "info" method, not the "info" method.
}
private static Logger getFor(Class<?> clazz) { return LOGGERS.computeIfAbsent(clazz, key -> LogManager.getLogger(key)); }
private static Class<?> getCallerClass() {
try {
return Class.forName(getCaller(3).getClassName());
} catch (ClassNotFoundException e) {
return LogUtils.class;
}
}
// This method should return "main" method name, but it's not being used because I don't know what should I do now
private static String getCallerMethod() { return getCaller(3).getMethodName(); }
private static StackTraceElement getCaller(int level) { return Thread.currentThread().getStackTrace()[level]; }
}
我已阅读several log4j2 documentation pages,但我没有发现任何关于我的问题,我还检查了several stack overflow questions,但似乎whatever I try to search 的结果是completely different question。
这甚至可能吗?因为我开始怀疑了。表示我试图避免在每个班级使用记录器......否则我不会问这个问题。至少可以创建一个记录自定义堆栈跟踪级别的自定义记录器?
附带说明一下,我的 Maven 依赖项是 the ones given on the log4j2 page:
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.14.1</version>
</dependency>
</dependencies>
我还必须提到,在一个答案中,有这个电话:
LOG.log(LoggingHelper.class.getCanonicalName(), Level.INFO, message, null);
我在org.apache.logging.log4j.Logger 中找不到这样的方法(类似Javadoc):
Logger#log(String, Level, Object, Throwable);
它只是不存在。
【问题讨论】: