我正在努力减少我的应用程序中的代码行。为了进行日志记录,我在前面的每个类中创建了一个方法来检索类和方法的名称。
public String currentClassAndMethod() {
// getStackTrace()[1] method return implementing method name at 1st index
return "Inside class: " + getClass().getSimpleName() + " in method name: "
+ new Throwable().getStackTrace()[1].getMethodName();
}
上面的方法在实现类(Controller、Service类等)中工作得很好,但是当我把它放在Util类中时,它给出了Util类的名称。
@GetMapping("/products")
public List<Product> getProducts() {
logger.info(ecommUtils.currentClassAndMethod());
List<Product> productList = productService.getProducts();
return productList;
}
我不能让这个方法是静态的。我想要实现的是在一个地方定义这个方法,然后从每个类调用这个方法。
发布于 2020-09-11 05:55:07
你在这里有一些严重的问题:
getStackTrace()
真的很慢。currentClassAndMethod()
方法所在的类,因此不是您想要的。这是可行的:int nestingLevel = 1;
StackTraceElement elem = new Throwable().getStackTrace[nestingLevel];
return elem.getFileName() + "::" + elem.getMethodName() + "::" + elem.getLineNumber();
// there is elem.getClassName() too if you prefer that.
你就是这么做的..。如果你想做的话。我建议您不要这样做。如果您必须这样做,请注意,如果您在日志基础结构中调用“获取位置”代码,例如在日志处理程序中(我不知道您使用了什么日志框架,所以我必须对其含糊不清),那么您可以大大加快速度--这样,如果您将日志记录设置在一个您忽略的级别上,您就不需要花费昂贵的时间来获取堆栈跟踪,只为了让生成的字符串通过日志记录基础结构,而被完全忽略,因为它低于配置的‘日志在这个级别’。
https://stackoverflow.com/questions/63848180
复制