log4j: Class name showing in log is not correct when I call the logger from another class

霸气de小男生 提交于 2019-12-24 02:59:04

问题


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");

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.

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);
}
}

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

I expect this

 INFO [main] (MyClass.java:18) - Hello, World

Where am I going wrong?


回答1:


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);
}

and your log4j configuration contains your pattern:

%d{ISO8601} %c %m %n

and this will print

2014-02-21 14:38:120 YourCategory Your Message

So you do not need to mess up with instatiation of Logger for each class with log.




回答2:


you are using logger.info(message); inside Logger class so always Logger.java you will get in your log file.

You can log the message inside the class in which you want to log, the classname will be logged.




回答3:


You don't use the class parameter in obtaining the log4j logger, so log4j assumes your logger class. Try

public static void INFO(Object oClass, String message){
   org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(oClass.getClass());
   logger.info(message);
}

instead.



来源:https://stackoverflow.com/questions/21935367/log4j-class-name-showing-in-log-is-not-correct-when-i-call-the-logger-from-anot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!