1. The background
Recently, while writing a new SPI-based logging framework, I initially threw an exception to block the system when I judged that there was no current instance of an Appender. After the Review, Yangge suggested that “catch all exceptions of the logging framework, do not affect the normal logic of the application”.
2. Solutions
- Referring to the Slf4j implementation, only error logs are printed when no instance of an Appender is found.
- SessionLogger sets up dynamic proxies to catch all of its methods and avoid exceptions from floating up.
private static final ThreadLocal<ISessionLogger> loggerThreadLocal = new ThreadLocal() {
private final IAppender appender = AppenderFactory.getAsyncAppender();
@Override
protected ISessionLogger initialValue() {
ISessionLogger sessionLogger = new SessionLoggerImpl();
sessionLogger.setAppender(appender);
return (ISessionLogger) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class[]{ISessionLogger.class},
(proxy, method, args) -> {
try {
Object ret = method.invoke(sessionLogger, args);
return ret;
} catch (Throwable throwable) {
returnnull; }}); }};Copy the code
3. The reflection
The exception handling logic of a system should be considered in modules, considering the position of the module in the system.
- The log frame is the auxiliary module of the system. Its exceptions cannot float up to the application logic, that is, the logging exceptions cannot affect the entire system’s business processing.
- The Maven plugin was recently developed to compile the run packages on the build line. If an exception is executed, the generated code is most likely wrong. Be sure to throw an exception at this point to interrupt the Maven packaging process and avoid running the wrong code.