我编写了一个庞大的Web应用程序并且“忘记”包含日志记录(我只使用标准的e.printStackTrace()方法打印错误。)
我的问题是,如果有任何方法可以自动记录(getLogger.LOG(SEVERE,“......”))任何抛出的异常吗?
可能使用exceptionFactory JSF中的自定义例外工厂?
我想用记录器记录每个抛出的异常,例如在程序进入catch-block之前,必须记录异常:
try{
...
} catch(Exception1 e){
//Exception must have been already logged here (without adding getLogger().LOG(...) every time)
System.out.println(e.printStackTrace());
} catch(Exception2 e){
//Exception must have been already logged here (without adding getLogger().LOG(...) every time)
System.out.println(e.printStackTrace());
}
答案 0 :(得分:1)
查看aspect oriented programming,它可以在运行时为您喜欢的日志记录框架插入日志记录代码。 JDK包含java.lang.instrument包,它可以在类加载期间插入字节码以执行日志记录。
否则,您可以安装servlet Filter作为调用链中最顶层的过滤器,它将捕获大部分异常。
public class LogFilter implements javax.servlet.Filter {
private static final String CLASS_NAME = LogFilter.class.getName();
private static final Logger logger = Logger.getLogger(CLASS_NAME);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
logger.entering(CLASS_NAME, "doFilter", new Object[]{request, response});
try {
chain.doFilter(request, response);
} catch (IOException | ServletException | RuntimeException | Error ioe) {
logger.log(Level.SEVERE, "", ioe);
throw ioe; //Keep forwarding.
} catch (Throwable t) {
logger.log(Level.SEVERE, "", t);
throw new ServletException(t);
}
logger.exiting(CLASS_NAME, "doFilter");
}
@Override
public void destroy() {
}
}
答案 1 :(得分:0)
您可以使用Thread.setUncaughtExceptionHandler()方法为主线程和您创建的所有其他线程设置未捕获的异常处理程序,并在那里执行所有必需的日志记录。
答案 2 :(得分:0)
我现在也在新的大项目前面,并且有兴趣消除不必要的代码。首先,我想记录每个进入和退出方法,包括输入和输出数据。在我的事件驱动架构的情况下,我推动这些数据弹性并连续分析方法处理超时,这是很多代码行。所以我用AspectJ处理了这个问题。非常好的例子是: http://www.baeldung.com/spring-performance-logging
同样适用于自动错误记录,这里是虚拟示例,我将扩展为使用slf4j,但这些是详细信息:
public aspect ExceptionLoggingAspect {
private Log log = LogFactory.getLog(this.getClass());
private Map loggedThrowables = new WeakHashMap();
public pointcut scope(): within(nl.boplicity..*);
after() throwing(Throwable t): scope() {
logThrowable(t, thisJoinPointStaticPart,
thisEnclosingJoinPointStaticPart);
}
before (Throwable t): handler(Exception+) && args(t) && scope() {
logThrowable(t, thisJoinPointStaticPart,
thisEnclosingJoinPointStaticPart);
}
protected synchronized void logThrowable(Throwable t, StaticPart location,
StaticPart enclosing) {
if (!loggedThrowables.containsKey(t)) {
loggedThrowables.put(t, null);
Signature signature = location.getSignature();
String source = signature.getDeclaringTypeName() + ":" +
(enclosing.getSourceLocation().getLine());
log.error("(a) " + source + " - " + t.toString(), t);
}
}
}
我很高兴听到还有什么是锅炉板代码减少的好例子。我当然使用Loombok来完成任务......
注意:不要重新发明轮,所以看看其他人收集有用的AOP,以便在您的项目中重复使用:-))开源是一个伟大的社区:{{3} }