如何使用 log4j 在 Java 中获取当前类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15615532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the current class name in Java with log4j
提问by user1787641
am using log4j for logging, in order to get the class name of the of the respective methods while executing, i got some common method which uses SecurityManager to get the class name, but i dont want to use SecurityManager, is their any other way to get the class name during runtime. Also i dont want to write the code(MyClass.getClassName
) to get the classname in each and every class.
我正在使用 log4j 进行日志记录,为了在执行时获取相应方法的类名,我得到了一些使用 SecurityManager 获取类名的常用方法,但我不想使用 SecurityManager,是他们的任何其他方法在运行时获取类名。此外,我不想编写代码(MyClass.getClassName
)来获取每个类中的类名。
class log extends SecurityManager {
public String getClassName() {
return getClassContext()[3].getName();
}
}
回答by Michal
Solution for static logger:
静态记录器的解决方案:
private static final Logger LOG = Logger.getLogger(new Object() { }.getClass().getEnclosingClass());
回答by Cao Minh
For the full name (with package):
全名(带包):
this.getClass().getName();
For the name of the class (just class name and no more):
对于班级名称(仅班级名称,仅此而已):
this.getClass().getSimpleName();
回答by Matthias Meid
Instead of receiving the class name, you can also receive a Logger
with the class object itself:
除了接收类名之外,您还可以接收Logger
带有类对象本身的 a:
public static Logger getLogger(Class clazz)
This is how it's used:
这是它的使用方式:
private static final Logger logger = Logger.getLogger(MyClass.class);
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Logger.html#getLogger(java.lang.Class)
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Logger.html#getLogger(java.lang.Class)
回答by Simulant
you could add the %l
to your PatternLayoutin the appender configuration to get the calling class of your log statement.
您可以在 appender 配置中添加%l
到PatternLayout以获取日志语句的调用类。
回答by Markus Kreth
I guess you need the class name of the class that is calling your log class?
我猜您需要调用日志类的类的类名?
Try this:
试试这个:
StackTraceElement stackTraceElement = new Throwable().getStackTrace()[3];
回答by Shreyos Adikari
You can do in this way too:
你也可以这样做:
private static final String CLASS_NAME = MyClass.class.getName();
log.debug(new LogRecord(CLASS_NAME," Success = "+isSuccess));