正如@Remko Popma 所说,这是一个简单的实现:
首先创建您的 ExtendedLogger 类:
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.spi.AbstractLogger;
import org.apache.logging.log4j.spi.ExtendedLoggerWrapper;
public class ExtLogWithLine extends ExtendedLoggerWrapper {
private static final long serialVersionUID = 8239280349129059055L;
// define your wrapper class here
private static final String FQCN = WrapperLog.class.getName();
private final ExtendedLoggerWrapper logger;
private ExtLogWithLine(final Logger logger) {
super((AbstractLogger) logger, logger.getName(), logger.getMessageFactory());
this.logger = this;
}
public static ExtLogWithLine create(final String name) {
final Logger wrapped = LogManager.getLogger(name);
return new ExtLogWithLine(wrapped);
}
@Override
public void debug(String info) {
if (isDebugEnabled()) {
logger.logIfEnabled(FQCN, Level.DEBUG, null, info, (Throwable) null);
}
}
@Override
public void info(String info) {
if (isInfoEnabled()) {
logger.logIfEnabled(FQCN, Level.INFO, null, info, (Throwable) null);
}
}
@Override
public void warn(String info) {
if (isWarnEnabled()) {
logger.logIfEnabled(FQCN, Level.WARN, null, info, (Throwable) null);
}
}
@Override
public void error(String info) {
if (isErrorEnabled()) {
logger.logIfEnabled(FQCN, Level.ERROR, null, info, (Throwable) null);
}
}
}
然后使用扩展的记录器打印日志:
public class WrapperLog {
public void testLog() {
ExtLogWithLine logger = ExtLogWithLine.create("xxx");
// log will print out with correct line number
logger.info("see the line number");
}
}