我必须在我的日志记录系统中添加自定义方法方法。让我们说我在几个地方的代码行如下:
private static Logger LOGGER = LoggerFactory.getLogger(MyJavaClass.class);
记录由slf4j处理。如何通过添加public void error(SomeTypeObject obj) { /implementation/ }
目标是不更改现有代码。如何强制LoggerFactory返回我自己的Logger实现,并使用上述方法进行扩展?
我按照这个问题的答案:stackoverflow.com/questions/2653855/implement-custom-logger-with-slf4j
所以,我已经制作了我的LoggerFactory,StaticLoggerBinder和MyLoggerAdapter。
StaticLoggerBinder
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();
}
}
MyLogger
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)
时,该方法不可见。我错过了什么。我非常感谢你的帮助。
答案 0 :(得分:0)
在您的MyJavaClass
中,您应该使用MyLoggerFactory
:
private static MyLoggerAdapter LOGGER = MyLoggerFactory.getLogger();
代替
private static Logger LOGGER = LoggerFactory.getLogger(MyJavaClass.class);
答案 1 :(得分:0)
在此示例中,记录器可以做到:
private static MyLoggerAdapter log = (MyLoggerAdapter) StaticLoggerBinder.getSingleton().getLoggerFactory.getLogger(MyController.class.getName());