log4j:当我从另一个班级调用记录器时,日志中显示的班级名称不正确 [英] log4j: Class name showing in log is not correct when I call the logger from another class
问题描述
基本上,当使用log4j时,我知道我们必须使用Logger.getLogger(MyClass.class)或Logger.getLogger("MyClass")来启动Logger.
Basically, when using log4j, I know we have to initiate a Logger by using Logger.getLogger(MyClass.class) or Logger.getLogger("MyClass").
我的课程太多了,我不想在每个课程中都添加此语句.相反,我想做的就是这个
I have too many classes and I dont want to add this statement in every class. Rather, what I woudl like to do is this
Logger.info(this,"My message");
其中Logger是我编写的类(不是log4j中的类),该类又会初始化Logger类型的对象(org.apache.log4j.Logger)并继续执行消息.
Where Logger is a class I have written (not the one in log4j) which in turn initiates an object of type Logger (org.apache.log4j.Logger) and carries on with the message.
这是我的Logger.java
This is my Logger.java
package com.mypackage;
/**
* @author Sriram Sridharan
*Custom logging implementation using log4j
*/
public class Logger {
private static org.apache.log4j.Logger logger;
/**
* Writes an INFO log
* @param oClass
* @param message
*/
public static void INFO(Object oClass, String message){
org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(oClass.getClass());
logger.info(message);
}
}
现在,我有我自己的类,该类调用此Logger实现来记录事件.看起来像这样
Now, I have my own class, that calls this Logger implementation to log events. it looks like this
public class MyClass {
public void myMethod(){
com.mypackage.Logger.INFO(this, "Hello, World");
}
}
我的日志没有问题.他们很好.但是,日志中显示的类名称是相同的(日志记录器).这是输出
I don't have a problem with the logs. They're fine. However, the Class name displayed in the logs is the same (Logger). This is the output
INFO [main] (Logger.java:18) - Hello, World
我希望如此
INFO [main] (MyClass.java:18) - Hello, World
我要去哪里错了?
推荐答案
使用%c
模式输出类别/getLogger("myCategory")
/而不是输出打印呼叫者类的%C
.
Use %c
pattern to output category /getLogger("myCategory")
/ instead of %C
that prints caller class.
想法是您拥有通用方法:
The idea is that you have generic method:
public static void debug(String category, String message) {
Logger logger = org.apache.log4j.Logger.getLogger(category);
logger.debug(message);
}
,您的log4j配置包含您的模式:
and your log4j configuration contains your pattern:
%d{ISO8601} %c %m %n
这将打印
2014-02-21 14:38:120 YourCategory Your Message
因此,您无需为每个带有日志的类弄乱Logger的实例化.
So you do not need to mess up with instatiation of Logger for each class with log.
这篇关于log4j:当我从另一个班级调用记录器时,日志中显示的班级名称不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!