如何将异常写入日志文件......?

时间:2014-10-17 15:08:32

标签: java spring-mvc

我使用的是Spring MVC ......

调度程序servlet加载后,我得到异常。我需要将该异常写入日志文件......

我收到错误...与主机192.168.100.178,端口1433的TCP / IP连接失败。错误:"连接超时。验证连接属性。确保主机上正在运行SQL Server实例并接受端口上的TCP / IP连接。确保防火墙不阻止与端口的TCP连接。"

我无法写入日志文件......

有人可以帮忙吗?感谢

3 个答案:

答案 0 :(得分:0)

一旦捕获到所有TCP / IP连接异常,就可以创建自己的自定义异常。抛出自定义异常后,您只需将日志写入指定的文件即可。

答案 1 :(得分:0)

您可以使用Log4j

Here是一个很好的教程,可以关注

答案 2 :(得分:0)

Log4j 2配置:

<?xml version="1.0" encoding="UTF-8"?>

<!-- No need to set system property "Log4jContextSelector" to any value
when using <asyncLogger> or <asyncRoot>. -->

<Configuration status="WARN">
    <Appenders>
    <!-- Async Loggers will auto-flush in batches, so switch off immediateFlush. -->
        <RandomAccessFile name="RandomAccessFile" fileName="asyncWithLocation.log"
            immediateFlush="false" append="false">
            <PatternLayout>
                <Pattern>%d %p %class{1.} [%t] %location %m %ex%n</Pattern>
            </PatternLayout>
        </RandomAccessFile>
    </Appenders>
    <Loggers>
    <!-- pattern layout actually uses location, so we need to include it -->
        <AsyncLogger name="com.foo.Bar" level="trace" includeLocation="true">
            <AppenderRef ref="RandomAccessFile"/>
        </AsyncLogger>
        <Root level="info" includeLocation="true">
            <AppenderRef ref="RandomAccessFile"/>
        </Root>
    </Loggers>
</Configuration>

以上配置取自Mixing Synchronous and Asynchronous Loggers

您可以在日志文件中添加例外: -

Logger logger = LogManager.getLogger(Your_Class_Name.class);
try {
    // do something
} catch (Exception e) {
    StringWriter stack = new StringWriter();
    e.printStackTrace(new PrintWriter(stack));
    logger.fatal(stack.toString());
};