How create log4j wrap and get correct logs
I have multithreaded application and i want add some text information in every log message I create factory and extend class, it works fine
开发者_如何转开发...
protected Logger logger = Logger.getLogger("Test", new MyLog4JFactory());
...
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;
public class MyLog4JFactory implements LoggerFactory{
@Override
public Logger makeNewLoggerInstance(String arg0) {
return new MyLogger(arg0);
}
}
import org.apache.log4j.Logger;
public class MyLogger extends Logger{
protected MyLogger(String name) {
super(name);
}
private String getMessage(Object msg){
StringBuffer sb = new StringBuffer();
return sb.append(msg).append(" ").append("My text").toString();
}
@Override
public void debug(Object message) {
super.debug(getMessage(message));
}
@Override
public void error(Object message) {
super.error(getMessage(message));
}
@Override
public void fatal(Object message) {
super.fatal(getMessage(message));
}
@Override
public void info(Object message) {
super.info(getMessage(message));
}
@Override
public void warn(Object message) {
super.warn(getMessage(message));
}
}
but! in the logs I see the wrapper class
all logs print as
2011-09-08 10:45:49,359 DEBUG MyLogger (35) - Test1 My text
What should I do to the log file shows a classes (with line number) calls my logger?
I know this is an old question, but I would like to share a nice solution I found:
Add FQCN to your class, call Logger.log method and pass it your FQCN like so:
public class MyLogger extends Logger{
private static String FQCN = MyLogger.class.getName();
...
@Override
public void debug(Object message) {
super.log(FQCN, org.apache.log4j.Level.DEBUG,message, null);
}
@Override
public void debug(Object message,Throwable t) {
super.log(FQCN, org.apache.log4j.Level.DEBUG,message, t);
}
}
(same will work for creating a wrapper...)
In your log4j.properties file, remove the %l
specifier from the line that looks something like this:
log4j.appender.A1.layout.ConversionPattern=<...>
ConversionPattern
could be PatternLayout
or something else. This will prevent the fully qualified calling class name and line number from being displayed.
More information on the specifiers can be found here.
精彩评论