我想将我的 Maven 项目中的所有异常(在控制台中显示)记录到一个文件中。我创建一个实现 UncaughtExceptionHandler 的类并调用 log4j Logger.error。这适用于主 Maven 项目(其中是 Main 类),但不适用于连接的其他 Maven 项目(所有 pom.xml 中都有依赖项)。也许默认的 UncaughtExceptionHandler 被 Maven 覆盖,但我怎样才能让它工作呢?
public static void main(String[] args) throws Exception{
Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
}
public class DefaultExceptionHandler implements UncaughtExceptionHandler{
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultExceptionHandler.class);
@Override
public void uncaughtException(Thread thread, Throwable ex) {
LOGGER.error("Exception thread: "+thread.getName(), ex);
}
}
最佳答案
您可以创建 java.io.PrintStream
实例,如下所示
public static PrintStream createLoggingProxy(
final PrintStream realPrintStream)
{
return new PrintStream(realPrintStream)
{
public void print(final String string)
{
logger.info(string);
}
public void println(final String string)
{
logger.warn(string);
}
};
}
并将其设置为适当的流,如下所示:
System.setOut(createLoggingProxy(System.out));
System.setErr(createLoggingProxy(System.err));
其中logger
是org.apache.log4j.Logger
的实例
关于Java UncaughtExceptionHandler + LOG4J + Maven,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32200777/