日志记录~log4.net

1. 添加Log4net引用

2. 添加配置文件

 Log.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <log4net>
    <logger name="Log4NetTest">
      <level value="ERROR"/>
      <appender-ref ref="Log4NetTestAppender" />
        <!--Log4NetTestAppender和下面进行对应-->
    </logger>

    <logger name="RYJ.Crm.Quartz">
      <level value="ERROR"/>
      <appender-ref ref="QuartzAppender" />
    </logger>

    <logger name="RYJ.Crm.Services">
      <level value="ERROR"/>
      <appender-ref ref="ServiceAppender" />
    </logger>

    <logger name="RYJ.Crm.ExternalService">
      <level value="ERROR"/>
      <appender-ref ref="ExternalServiceAppender" />
    </logger>

    <logger name="RYJ.Crm.HeartBeat">
      <level value="DEBUG"/>
      <appender-ref ref="HeartBeatAppender" />
    </logger>

    <logger name="RYJ.Crm.System">
      <level value="ERROR"/>
      <appender-ref ref="SystemAppender" />
    </logger>

    <logger name="RYJ.Crm.UrlFilter">
      <level value="DEBUG"/>
      <appender-ref ref="UrlFilterAppender" />
    </logger>

    <logger name="NHibernate">
      <level value="OFF"/>
      <appender-ref ref="NHibernateAppender" />
    </logger>

    <logger name="RYJ.Return">
      <level value="DEBUG"/>
      <appender-ref ref="ReturnAppender" />
    </logger>

    <logger name="RYJ.Crm.Event">
      <level value="DEBUG"/>
      <appender-ref ref="EventAppender" />
    </logger>

    <logger name="RYJ.Crm">
      <level value="ERROR"/>
      <appender-ref ref="EmailAppender" />
    </logger>

    <!--返回值异常日志记录-->
    <appender name="Log4NetTestAppender" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="Logs/Log4NetTest/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyy-MM-dd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>

    <!--返回值异常日志记录-->
    <appender name="ReturnAppender" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="Logs/Return/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyy-MM-dd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>

    <!--事件异常日志记录-->
    <appender name="EventAppender" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="Logs/Event/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyy-MM-dd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>

    <!--系统异常日志记录-->
    <appender name="SystemAppender" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="Logs/System/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyy-MM-dd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>

    <!--调度日志记录-->
    <appender name="QuartzAppender" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="Logs/Quartz/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyy-MM-dd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>

    <!--Service日志记录-->
    <appender name="ServiceAppender" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="Logs/Service/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyy-MM-dd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>

    <!--调用外部服务日志记录-->
    <appender name="ExternalServiceAppender" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="Logs/ExternalService/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyy-MM-dd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>

    <!--HeartBeat日志记录-->
    <appender name="HeartBeatAppender" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="Logs/HeartBeat/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyy-MM-dd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>

    <!--UrlFilter日志记录-->
    <appender name="UrlFilterAppender" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="Logs/UrlFilter/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyy-MM-dd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>

    <!--NHibernate日志记录-->
    <appender name="NHibernateAppender" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="Logs/NHibernate/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyy-MM-dd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>

    <!--邮箱设置-->
    <appender name="EmailAppender" type="log4net.Appender.SmtpAppender">
      <!-- SMTP 验证方式 -->
      <authentication value="Basic" />
      <to value="" />
      <from value="service@daishu360.com" />
      <username value="service@daishu360.com" />
      <password value="DSpuhui360.cn" />
      <subject value="【本地环境】CRM后台API错误异常" />
      <!--邮件服务端-->
      <smtpHost value="smtp.exmail.qq.com"/>
      <bufferSize value="10240" />
      <lossy value="true" />
      <!--这里我设置的是Error ,会接收(FATAL和ERROR日志)你可以根据自己的需要设置Log4net支持多种级别的日志。优先级从高到低依次排列如下:FATAL > ERROR > WARN > INFO > DEBUG-->
      <evaluator type="log4net.Core.LevelEvaluator">
        <threshold value="OFF"/>
      </evaluator>
      <!--输出格式-->
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>
  </log4net>
</configuration>
View Code

 Web.config

 <!--log4net日志配置文件-->
    <add key="log4net" value="config/log4net/log.config" />

3. 注册lognet

  protected void Application_Start()
        {          

            //注册lognet
            var log4NetFileName = FilePath(ConfigurationManager.AppSettings["log4net"]);
            if (File.Exists(log4NetFileName))
            {
                XmlConfigurator.ConfigureAndWatch(new FileInfo(log4NetFileName));
            }
        }
        private static string FilePath(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return string.Empty;
            }

            return string.Format("{0}/{1}", AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\', '/'), name.TrimStart('\\', '/'));
        }
View Code

4. 编写Helper

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Log4NetTest
{
    public static class Log4NetUtility
    {
        /// <summary>
        ///     写日志
        /// </summary>

        public static void WriteLog(this string message, string name, Log4NetType logType = Log4NetType.Info)
        {
            var log = GetLog(name);
            if (log == null)
            {
                return;
            }

            if (logType == Log4NetType.Debug)
            {
                log.Debug(message);
                return;
            }

            if (logType == Log4NetType.Error)
            {
                log.Error(message);
                return;
            }

            if (logType == Log4NetType.Fatal)
            {
                log.Debug(message);
                return;
            }

            if (logType == Log4NetType.Info)
            {
                log.Info(message);
                return;
            }

            log.Warn(message);
        }

        /// <summary>
        ///     写异常日志
        /// </summary>
        public static void WriteLog(this Exception exception, string name)
        {
            var log = GetLog(name);
            if (log == null)
            {
                return;
            }

            WriteLog(exception, log);
        }

        /// <summary>
        ///     写异常日志
        /// </summary>
        private static void WriteLog(Exception exception, ILog log)
        {
            if (exception == null)
            {
                return;
            }

            log.Error(exception);

            WriteLog(exception.InnerException, log);
        }

        /// <summary>
        ///     获取日志对象
        /// </summary>
        public static ILog GetLog(string name)
        {
            var logger = LogManager.GetLogger(name);
            return logger;
        }
    }

    /// <summary>
    ///     Log4Net类型枚举
    /// </summary>
    public enum Log4NetType
    {
        /// <summary>
        ///     字段Debug
        /// </summary>

        Debug,

        /// <summary>
        ///     字段Error
        /// </summary>
        Error,

        /// <summary>
        ///     字段Info
        /// </summary>
        Info,

        /// <summary>
        ///     字段Fatal
        /// </summary>
        Fatal,

        /// <summary>
        ///     字段Warn
        /// </summary>
        Warn
    }

    /// <summary>
    ///     类名称:Log4NetName
    ///     命名空间:DaiShu.Crm.Utility
    ///     类功能:日志名称
    /// </summary>
    public class Log4NetName
    {
        /// <summary>
        ///     字段UrlFilter
        /// </summary>     
        public const string Log4NetTest = "Log4NetTest";

        /// <summary>
        ///     字段UrlFilter
        /// </summary>       
        public const string UrlFilter = "RYJ.Crm.UrlFilter";

        /// <summary>
        ///     字段System
        /// </summary>      
        public const string System = "RYJ.Crm.System";

        /// <summary>
        ///     字段Quartz
        /// </summary>       
        public const string Quartz = "RYJ.Crm.Quartz";

        /// <summary>
        ///     字段Service
        /// </summary>       
        public const string Service = "RYJ.Crm.Services";

        /// <summary>
        ///     字段ExternalService
        /// </summary>     
        public const string ExternalService = "RYJ.Crm.ExternalService";

        /// <summary>
        ///     字段Return
        /// </summary>     
        public const string Return = "RYJ.Return";

        /// <summary>
        ///     字段HeartBeat
        /// </summary>       
        public const string HeartBeat = "RYJ.Crm.HeartBeat";

        /// <summary>
        /// 字段Event
        /// </summary>      
        public const string Event = "RYJ.Crm.Event";
    }
}
View Code

调用演示

            try
            {
                int n=int.Parse("aaa");
            }
            catch (Exception ex)
            {
                ex.WriteLog(Log4NetName.Log4NetTest);
            }

 下载源码

posted @ 2017-10-03 15:01  shuai7boy  阅读(212)  评论(0编辑  收藏  举报