Log4net简单使用

    log4net是一个非常流行的.NET日志记录组件,本文介绍其简单应用。

    1、引用log4net组件。

    2、新建解决方案Log4NetTest,其中有两个项目:Log4NetCommon作为公共项目,Log4NetTest项目作测试。

    3、在Log4NetCommon的AssemblyInfo.cs文件中加入以下代码:

[assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFile = "log4net.config")]

    4、添加日志配置文件log4net.config,设置为内容较更新则复制,其内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  <log4net>
    <logger name="ErrorLogger">
      <level value="INFO"/>
      <appender-ref ref="ErrorLoggerRollingFileAppender_Txt"/>
      <appender-ref ref="rootConsole" />
    </logger>

    <!--输出介质-->
    <appender name="ErrorLoggerRollingFileAppender_Txt" type="log4net.Appender.RollingFileAppender">
      <file value="ErrorLogs\Error" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value=".yyyy.MM.dd.'log'"/>
      <staticLogFileName value="false" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[%date][%-5level]…%message %newline" />
      </layout>
    </appender>

    <appender name="rootConsole"  type="log4net.Appender.ConsoleAppender" >

      <layout type="log4net.Layout.PatternLayout">

        <param name="ConversionPattern"  value="[%date][%-5level]…%message %newline" />

      </layout>

    </appender>
    
  </log4net>
</configuration>

    5、编写日志帮助类LogHelper:

using log4net;
using log4net.Core;

namespace Log4NetCommon
{
    /// <summary>
    /// 日志帮助类
    /// </summary>
    public static class LogHelper
    {
        private static readonly ILog log = LogManager.GetLogger("ErrorLogger");

        public static void Error(string msg)
        {
            log.Error(msg);
        }
    }
}

    6、在主程序中测试:

using System;
using Log4NetCommon;

namespace Log4NetTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Log Test";
            LogHelper.Error("张三,你错了吗");
            Console.ReadLine();
        }
    }
}

 

posted @ 2015-11-05 10:50  捡贝壳的小哥  阅读(549)  评论(1编辑  收藏  举报