log4j: Class name showing in log is not correct wh

2019-07-17 07:24发布

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?

3条回答
祖国的老花朵
2楼-- · 2019-07-17 07:57

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楼-- · 2019-07-17 08:03

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.

查看更多
疯言疯语
4楼-- · 2019-07-17 08:07

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.

查看更多
登录 后发表回答