我必须将自定义方法方法添加到我的日志系统中。假设我有几行代码,例如:私有静态Logger LOGGER=LoggerFactory.getLogger(MyJavaClass.class);
日志记录由slf4j处理。如何通过添加新(!)扩展我的记录器方法,如public void error(SomeTypeObject obj){/implementation/}
目标是不更改现有代码。如何强制LoggerFactory返回使用上述方法扩展的自己的记录器实现?
我跟踪了这个问题的答案:stackoverflow.com/questions/2653855/implement-custom-logger-with-slf4j
所以,我做了我的LoggerFactory,StaticLoggerBinder和MyLoggerAdapter。
静态日志
public class StaticLoggerBinder implements LoggerFactoryBinder {
private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
public static final StaticLoggerBinder getSingleton() {
return SINGLETON;
}
public static String REQUESTED_API_VERSION = "1.6.99";
private static final String loggerFactoryClassStr = MyLoggerFactory.class.getName();
private final ILoggerFactory loggerFactory;
private StaticLoggerBinder() {
loggerFactory = new MyLoggerFactory();
}
public ILoggerFactory getLoggerFactory() {
return loggerFactory;
}
public String getLoggerFactoryClassStr() {
return loggerFactoryClassStr;
}
}
记录器工厂
public class MyLoggerFactory implements ILoggerFactory {
ConcurrentMap<String, Logger> loggerMap;
public MyLoggerFactory() {
loggerMap = new ConcurrentHashMap<String, Logger>();
}
public Logger getLogger(String name) {
Logger simpleLogger = loggerMap.get(name);
if (simpleLogger != null) {
return simpleLogger;
} else {
Logger newInstance = new MyLoggerAdapter(name);
Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
return oldInstance == null ? newInstance : oldInstance;
}
}
void reset() {
loggerMap.clear();
}
}
迈洛格
public class MyLoggerAdapter implements Logger {
//methods from Logger interface
//and my additional method
public void error(Exception ex) {
//do smthng;
}
}
现在,在MyJavaClass中,我有一个字段private static Logger Logger=LoggerFactory。getLogger(MyJavaClass.class)代码>
问题是,当我尝试LOGGER. error(myExceptionObject)
时,该方法不可见。我错过了一些东西。我将非常感谢帮助。
在MyJavaClass中,应该使用MyLoggerFactory:
private static MyLoggerAdapter LOGGER = MyLoggerFactory.getLogger();
而不是
private static Logger LOGGER = LoggerFactory.getLogger(MyJavaClass.class);
在此示例中,记录器可以获得:
private static MyLoggerAdapter log = (MyLoggerAdapter) StaticLoggerBinder.getSingleton().getLoggerFactory.getLogger(MyController.class.getName());