WinForm下使用 log4net

在C# winForm程序中添加log4net

1. 引用 log4net.dll

2. 添加 app.config 内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <log4net>
        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
            <param name="File" value="Log\Log.txt" />
            <param name="AppendToFile" value="true" />
            <param name="MaxSizeRollBackups" value="100" />
            <param name="MaximumFileSize" value="2MB" />
            <param name="RollingStyle" value="Size" />
            <param name="StaticLogFileName" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%-5p %d [%c] %m%n" />
            </layout>
        </appender>
        <root>
            <level value="all" />
            <appender-ref ref="RollingLogFileAppender" />
        </root>
    </log4net>
</configuration>

具体设置说明可在网上找。

3. 在 Properties/AssemblyInfo.cs 添加 [assembly: log4net.Config.DOMConfigurator(Watch=true)]

4. 在代码中添加日志

定义LOG private static log4net.ILog LOG = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

写入日志 LOG.Info("窗体打开");

5. 如果要记录所有未处理异常,修改 Program.cs 如下 

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Reflection;
 
namespace ExceptionTest
{
    static class Program
    {
        static log4net.ILog LOG = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            //捕获未处理异常
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException +=new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
 
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
 
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            LOG.Error(e.Exception);
            //throw new Exception("线程未知异常", e.Exception);
            MessageBox.Show(e.Exception.Message, "线程异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Application.Exit();
        }
 
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            LOG.Error(ex);
            MessageBox.Show(ex.Message, "应用程序异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Application.Exit();
        }
    }
}

在Asp.net 网站中添加log4net

1. 引用 log4net.dll

2. 配置Web.config 如下

<?xml version="1.0"?>
 
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    </configSections>
    <appSettings/>
    <connectionStrings/>
    <system.web>
        <compilation debug="true"/>
        <authentication mode="Windows"/>
    </system.web>
 
    <!--日志-->
    <log4net>
        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
            <param name="File" value="D:\test\Log.txt" />
            <param name="AppendToFile" value="true" />
            <param name="MaxSizeRollBackups" value="100" />
            <param name="MaximumFileSize" value="2MB" />
            <param name="RollingStyle" value="Size" />
            <param name="StaticLogFileName" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%-5p %d [%c] %m%n" />
            </layout>
        </appender>
        <root>
            <level value="all" />
            <appender-ref ref="RollingLogFileAppender" />
        </root>
    </log4net>
</configuration>

3. 添加 Global.asax 内容如下:

private static log4net.ILog LOG = log4net.LogManager.GetLogger("Log4net 测试网站");
void Application_Start(object sender, EventArgs e)
{
    // 在应用程序启动时运行的代码
    log4net.Config.DOMConfigurator.Configure();
    LOG.Info("网站启动");
}
 
void Application_Error(object sender, EventArgs e)
{
    // 在出现未处理的错误时运行的代码
    Exception ex = HttpContext.Current.Server.GetLastError();
    LOG.Error("未处理异常", ex);
}

将站点的所有未处理异常记录到log4net中。

4. 如何使用

定义LOG private static log4net.ILog LOG = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

写入日志 LOG.Info("网站启动");

示例代码下载

下载:https://files.cnblogs.com/zjfree/ErrorLog.rar

posted @ 2015-05-21 14:35  伟大的厨师  阅读(345)  评论(0编辑  收藏  举报