我最近偶然发现现有应用程序中的以下日志代码行。这段代码在很多方面对我来说都是完全错误的
Method method = ...;// passed in as parameter
//...
String className = method.getDeclaringClass().getName();
String methodName = method.getName();
long id = Thread.currentThread().getId();
String name = Thread.currentThread().getName();
String msg = String.format("some text, for: %s %s in thread %d %s", className, methodName, id, name);
LOGGER.debug("xxxxxxxx {}", msg);
我想知道
(注意:正如{}
所示,它是一个SLF4J记录器,而xxxxxxxx
是一个唯一的字符串,用于在代码库中标识这个特殊的日志记录语句)
答案 0 :(得分:3)
日志记录是应用程序中的一个重要问题
所以对于一般情况,我使用拦截器/方面模式来做它。
String className = method.getDeclaringClass().getName();
String methodName = method.getName();
long id = Thread.currentThread().getId();
String name = Thread.currentThread().getName();
String msg = String.format("some text, for: %s %s in thread %d %s",
className, methodName, id, name);
在没有检查当前记录器的有效级别之前进行所有这些计算是没有意义的,因为即使没有写入日志也会应用它。
此外,如果需要并且在appender的模式中指定,API记录器可以检索所有这些信息。
此外,这也无效:
String msg = String.format("some text, for: %s %s in thread %d %s", className, methodName, id, name);
LOGGER.debug("xxxxxxxx {}", msg);
它还会在检查关卡之前格式化字符串。
使用实际代码,这是更好的:
if (LOGGER.isDebugEnabled()){
String className = method.getDeclaringClass().getName();
String methodName = method.getName();
long id = Thread.currentThread().getId();
String name = Thread.currentThread().getName();
String msg = String.format("some text, for: %s %s in thread %d %s", className, methodName, id, name);
LOGGER.debug("xxxxxxxx {}", msg);
}
但更强大的解决方案是使用appender模式使用Thread id,方法等来装饰日志信息......
最后作为一般方法,如果检查当前级别(此处:if (LOGGER.isDebugEnabled()){
)并不包含日志记录处理,例如:
String msg = String.format("some text, for: %s %s in thread %d %s", className, methodName, id, name);
LOGGER.debug("xxxxxxxx {}", msg);
使用带有var args的log方法更有效,因为它是为你的目的设计的而不是你的样本中使用的。
通过这种方式,如果有效记录器级别不匹配,它可以节省计算:
LOGGER.debug("some text, for: {} {} in thread {} {}", className, methodName, id, name);