log4net的应用

1.下载log4net

2编写log4net的配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
  </configSections>
  <appSettings>   </appSettings>
  <log4net debug="true">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="log//error_"/>
      <param name="AppendToFile" value="true"/>
      <param name="MaxSizeRollBackups" value="10"/>
      <param name="StaticLogFileName" value="false"/>
      <param name="DatePattern" value="yyyy-MM-dd".log""/>
      <param name="RollingStyle" value="Date"/>
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d - %m%n"/>
      </layout>
    </appender>
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
  </log4net>
</configuration>

  3编写帮助类

using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace TestData.Common
{
    public static class HadleExcption
    {
        //判断是否是绝对路径
        public static bool IsPhysicalPath(string Path)
        {
            string RegexString = @"\b[a-z]:\\.*";
            MatchCollection Matchs = Regex.Matches(Path, RegexString, RegexOptions.IgnoreCase | RegexOptions.Compiled);
            if (Matchs.Count > 0)
                return true;
            return false;
        }

        public static void WriteLog(this Exception ex, string message)
        {
            string _path = "";
            if (!IsPhysicalPath("~/Config/lognet.config"))
                _path = HttpContext.Current.Server.MapPath("~/Config");
            else _path = "~/Config/lognet.config";
            FileInfo info = null;
            if (new DirectoryInfo(_path).Exists)
            {
                info = new FileInfo(_path + "/lognet.config");
            }
            log4net.Config.XmlConfigurator.ConfigureAndWatch(info);
            log4net.ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
            log.Info(message, ex);

        }
    }
}

  

posted @ 2015-03-05 11:08  流浪的狸猫  阅读(241)  评论(0编辑  收藏  举报