Log4net 日志帮助类

Log4Net是DotNet开发中常用的日志处理类,这里介绍下在项目中假如Log4Net的配置方法。

步骤:

  1. 在项目中引用log4net.dll;
  2. 在配置文件中(app.config或web.config)加入log4net相关的项:

'''

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>

<log4net>
    <!--定义输出到文件中-->
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
        <!--定义文件存放位置-->
        <file value="log\\"/>
        <appendToFile value="true"/>
        <rollingStyle value="Date"/>
        <datePattern value="yyyyMMdd'.txt'"/>
        <staticLogFileName value="false"/>
        <param name="MaxSizeRollBackups" value="100"/>
        <layout type="log4net.Layout.PatternLayout">
            <!--输出格式-->
            <conversionPattern value=" %date : [%-5level] %message %newline"/>
        </layout>
    </appender>

    <appender name="RollingLogFileAppender_GlobalLog" type="log4net.Appender.RollingFileAppender" >
        <param name="File" value="Log\" />
        <encoding value="utf-8" />
        <param name="AppendToFile" value="true" />
        <param name="MaxSizeRollBackups" value="10" />
        <param name="MaximumFileSize" value="10MB" />
        <param name="RollingStyle" value="Composite" />
        <param name="DatePattern" value="yyyyMMdd\.\l\o\g" />
        <param name="StaticLogFileName" value="false" />
        <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
        <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%date: [%-5p] %m%n" />
        </layout>
    </appender>

    <appender name="RollingLogFileAppender_errorLog" type="log4net.Appender.RollingFileAppender" >
        <param name="File" value="Log\errlog_" />
        <encoding value="utf-8" />
        <param name="AppendToFile" value="true" />
        <param name="MaxSizeRollBackups" value="10" />
        <param name="MaximumFileSize" value="10MB" />
        <param name="RollingStyle" value="Composite" />
        <param name="DatePattern" value="yyyyMMdd\.\l\o\g" />
        <param name="StaticLogFileName" value="false" />
        <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%exception %n记录时间:%date %n线程ID:[%thread] %n日志级别:  %-5level %n出错类:%logger property: [%property{NDC}] - %n错误描述:%message%newline %n"/>
        </layout>
    </appender>

    <root>
        <level value="WARN" />
        <!--      <appender-ref ref="RollingLogFileAppender" /> -->
    </root>

    <logger name="info_log">
        <level value="DEBUG"/>
        <appender-ref ref="RollingLogFileAppender_GlobalLog" />
    </logger>

    <logger name="error_log">
        <level value="DEBUG"/>
        <appender-ref ref="RollingLogFileAppender_errorLog"/>
    </logger>

</log4net>

'''

  1. 添加LogHelper类:

'''

using System;
using System.Text;
using log4net;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace Log4NetDemo
{
/// <summary>
/// 日志类型
/// </summary>
public enum LOGTYPE
{
    /// <summary>
    /// 普通日志
    /// </summary>
    INFO = 1,
    /// <summary>
    /// 程序异常日志
    /// </summary>
    ERROR = 2,
}

public class LogHelper
{
    private static ILog info_log = null;
    private static ILog error_log = null;
    private static string infoLogName = "info_log";
    private static string errorLogName = "error_log";

    private static ILog GetInfoLogger()
    {
        if (info_log == null)
            info_log = LogManager.GetLogger(infoLogName);
        return info_log;
    }

    private static ILog GetErrorLogger()
    {
        if (error_log == null)
            error_log = LogManager.GetLogger(errorLogName);
        return error_log;
    }

    /// <summary>
    /// 输出异常信息到文件
    /// </summary>
    public static void WriteLog(Exception ex)
    {
        string msg = string.Format("{0}\r\n{1}\r\n{2}", ex.GetType().ToString(), ex.Message, ex.StackTrace);
        GetErrorLogger().Error(msg);
    }

    /// <summary>
    /// 输出日志到文件
    /// </summary>
    public static void WriteLog(string msg, LOGTYPE logtype = LOGTYPE.INFO)
    {
        switch (logtype)
        {
            case LOGTYPE.INFO:
                GetInfoLogger().Info(msg);
                break;
            case LOGTYPE.ERROR:
                GetErrorLogger().Error(msg);
                break;
            default:
                GetInfoLogger().Info(msg);
                break;
        }
    }

}
}

'''

4.在控制台程序中测试代码:

'''

    static void Main(string[] args)
    {
        try
        {
            LogHelper.WriteLog("this is the test message.", LOGTYPE.INFO);
            //抛出转换异常
            int.Parse("a"); 
        }
        catch (Exception ex)
        {
            LogHelper.WriteLog(ex);
        }

        Console.ReadKey();
    }

'''

结果在当前Debug目录下产生Log文件夹,及20160824.log, errlog_20160824.log两个文件:
文件内容分别为:

* 20160824.log *
    2016-08-24 16:28:14,073: [INFO ] this is the test message.

* errlog_20160824.log *
    记录时间:2016-08-24 16:28:14,116 
    线程ID:[8] 
    日志级别:  ERROR 
    出错类:error_log property: [(null)] - 
    错误描述:System.FormatException
    Input string was not in a correct format.
       at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
       at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
       at System.Int32.Parse(String s)
       at Log4NetDemo.Program.Main(String[] args) in c:\users\administrator\documents\visual studio 2010\Projects\Log4NetDemo\Log4NetDemo\Program.cs:line 17

注意事项

  1. 需要将项目的Target Framework切换至.Net Framework X, 而不能是.Net Framework X Client Profile.

END

标签: log4net

添加新评论