log4net无法处理进程退出

时间:2018-02-04 10:38:01

标签: c# log4net

如何在应用程序退出事件中使用log4net记录消息?

在示例中,我仅使用控制台appender进行日志记录:

<log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%message%newline"/>
        </layout>
    </appender>
    <root>
        <level value="INFO" />
        <appender-ref ref="ConsoleAppender" />
    </root>
</log4net>

在应用程序中,我想在ProcessExit事件上写下最终消息。

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

namespace ConsoleApplication3
{
    class Program
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("test");

        static void Main(string[] args)
        {
            log.Info("Application started");

            AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnApplicationExit);

            log.Info("Application is going to exit");
        }

        static void OnApplicationExit(object sender, EventArgs e)
        {
            Console.WriteLine("OnApplicationExit called");
            log.Info("Application exit");
            Console.WriteLine("OnApplicationExit exit");
        }
    }
}

这是我的输出:

Application started
Application is going to exit
OnApplicationExit called
OnApplicationExit exit

似乎在OnApplicationExit致电之前,appender已关闭。

是否有可能以某种方式在应用程序退出时记录任何消息?

1 个答案:

答案 0 :(得分:1)

你需要打电话

    AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnApplicationExit);

在实现log4net logger之前

class Program
{
    private static  log4net.ILog log = null;

    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnApplicationExit);
        log= log4net.LogManager.GetLogger("test");
        log.Info("Application started");



        log.Info("Application is going to exit");
    }

    static void OnApplicationExit(object sender, EventArgs e)
    {

        Console.WriteLine("OnApplicationExit called");
        log.Info("Application exit");
        Console.WriteLine("OnApplicationExit exit");
    }
}

结果: enter image description here