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?
you are using
logger.info(message);
insideLogger class
so alwaysLogger.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.
Use
%c
pattern to output category /getLogger("myCategory")
/ instead of%C
that prints caller class.The idea is that you have generic method:
and your log4j configuration contains your pattern:
and this will print
So you do not need to mess up with instatiation of Logger for each class with log.
You don't use the class parameter in obtaining the log4j logger, so log4j assumes your logger class. Try
instead.