码迷,mamicode.com
首页 > Web开发 > 详细

log4net配置+全局异常抓取防遗忘整理

时间:2017-10-13 12:32:07      阅读:772      评论:0      收藏:0      [点我收藏+]

标签:tac   csharp   hint   dna   自定义   目录   方式   tput   rri   

1 引用log4net.dll

技术分享

 

2 在web的根目录下添加config配置文件 log4net.config

技术分享

 

3 配置 log4net.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4Net" />
  </configSections>
  <log4net debug="true">

    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppenderByDate" />
      <appender-ref ref="AdoNetAppender" />
    </root>

    <logger name="WebLogger">
      <!--配置日志的级别,低于此级别的就不写到日志里面去-->
      <level value="DEBUG" />

    </logger>

    <!--按日期分割日志文件 一天一个-->
    <appender name="LogFileAppenderByDate" type="log4net.Appender.RollingFileAppender,log4net" >

      <!--是否续写-->
      <param name="AppendToFile" value="true" />
      <!--最小锁定模型以允许多个进程可以写入同一个文件-->
      <param name="LockingModel" value="log4net.Appender.FileAppender.MinimalLock" />
      <param name="StaticLogFileName" value="true" />
      <!--保存路径-->
      <param name="File" value="Log\\" />
      <param name="DatePattern" value="yyyy-MM-dd.LOG" />
      <param name="StaticLogFileName" value="false" />
      <param name="RollingStyle" value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d,%c%nLog:%m%n-----------------------------------------%n%n" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="DEBUG" />
        <param name="LevelMax" value="DEBUG" />
      </filter>
    </appender>

    <!--按日志容量分割日志文件 10KB一个-->
    <appender name="LogFileAppenderBySize" type="log4net.Appender.RollingFileAppender" >
      <!--是否续写-->
      <param name="AppendToFile" value="true" />
      <!--最小锁定模型以允许多个进程可以写入同一个文件-->
      <param name="LockingModel" value="log4net.Appender.FileAppender.MinimalLock" />

      <param name="StaticLogFileName" value="true" />

      <!--按照文件的大小进行变换日志文件-->
      <param name="RollingStyle" value="Size" />
      <param name="File" value="log.txt" />
      <!--单个文件最大数量 好像只有在 按Size分割时有效-->
      <param name="MaximumFileSize" value="200KB"/>
      <!--保留的log文件数量 超过此数量后 自动删除之前的   好像只有在 按Size分割时有效-->
      <param name="MaxSizeRollBackups" value="2" />

      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="发生时间:%d %n事件级别:%level %n相关类名:%c%n程序文件:%F 第%L行%n日志内容:%m%n-----------------------------------------%n%n" />
      </layout>
    </appender>

    <!--记录日志到数据库-->
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1" />
      <!--缓冲大小-->
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <connectionString value="Data Source=.\SQLEXPRESS;Initial Catalog=CVDS;User ID=sa;Password=sasa" />
      <commandText value="INSERT INTO Log([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
      <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout" />
      </parameter>
      <parameter>
        <parameterName value="@thread" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%thread" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_level" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@logger" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@exception" />
        <dbType value="String" />
        <size value="2000" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>
    </appender>

    <!-- 控制台前台显示日志 -->
    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
      <mapping>
        <level value="ERROR" />
        <foreColor value="Red, HighIntensity" />
      </mapping>
      <mapping>
        <level value="Info" />
        <foreColor value="Green" />
      </mapping>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" />
      </layout>

      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="Info" />
        <param name="LevelMax" value="Fatal" />
      </filter>
    </appender>



  </log4net>
</configuration>

4 配置Global.asax

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Server.MapPath("log4net.config")));//log4net
        }

5 在AssemblyInfo.cs中添加

 

技术分享

6 调用

技术分享
   public class LogHelper
    {
        //定义信息的二次处理
        public static event Action<string> OutputMessage;
        private static StackFrame sf = new StackTrace().GetFrame(2);//0为本身方法,1为调用方法,2为上一级调用方法
        private static string methodName = sf.GetMethod().Name;//方法名
        private static string calssName = sf.GetMethod().ReflectedType.Name;//类名
        //ILog对象
        private static readonly ILog log = LogManager.GetLogger(sf.GetMethod().DeclaringType);

        #region 定义信息二次处理方式
        private static void HandMessage(object Msg)
        {
            if (OutputMessage != null)
            {
                OutputMessage(Msg.ToString());
            }
        }
        private static void HandMessage(object Msg, Exception ex)
        {
            if (OutputMessage != null)
            {
                OutputMessage(string.Format("{0}:{1}", Msg.ToString(), ex.ToString()));
            }
        }
        private static void HandMessage(string format, params object[] args)
        {
            if (OutputMessage != null)
            {
                OutputMessage(string.Format(format, args));
            }
        }
        #endregion

        #region 封装Log4net
        public static void Debug(object message)
        {
            HandMessage(message);
            if (log.IsDebugEnabled)
            {
                log.Debug(message);
            }
        }
        public static void Debug(object message, Exception ex)
        {
            HandMessage(message, ex);
            if (log.IsDebugEnabled)
            {
                log.Debug(message, ex);
            }
        }
        public static void DebugFormat(string format, params object[] args)
        {
            HandMessage(format, args);
            if (log.IsDebugEnabled)
            {
                log.DebugFormat(format, args);
            }
        }

        //-----以下方法暂时不用,注释掉------
        /*
        public static void Error(object message)
        {
            HandMessage(message);
            if (log.IsErrorEnabled)
            {
                log.Error(message);
            }
        }
        public static void Error(object message, Exception ex)
        {
            HandMessage(message, ex);
            if (log.IsErrorEnabled)
            {
                log.Error(message, ex);
            }
        }
        public static void ErrorFormat(string format, params object[] args)
        {
            HandMessage(format, args);
            if (log.IsErrorEnabled)
            {
                log.ErrorFormat(format, args);
            }
        }
        public static void Fatal(object message)
        {
            HandMessage(message);
            if (log.IsFatalEnabled)
            {
                log.Fatal(message);
            }
        }
        public static void Fatal(object message, Exception ex)
        {
            HandMessage(message, ex);
            if (log.IsFatalEnabled)
            {
                log.Fatal(message, ex);
            }
        }
        public static void FatalFormat(string format, params object[] args)
        {
            HandMessage(format, args);
            if (log.IsFatalEnabled)
            {
                log.FatalFormat(format, args);
            }
        }
        public static void Info(object message)
        {
            HandMessage(message);
            if (log.IsInfoEnabled)
            {
                log.Info(message);
            }
        }
        public static void Info(object message, Exception ex)
        {
            HandMessage(message, ex);
            if (log.IsInfoEnabled)
            {
                log.Info(message, ex);
            }
        }
        public static void InfoFormat(string format, params object[] args)
        {
            HandMessage(format, args);
            if (log.IsInfoEnabled)
            {
                log.InfoFormat(format, args);
            }
        }
        public static void Warn(object message)
        {
            HandMessage(message);
            if (log.IsWarnEnabled)
            {
                log.Warn(message);
            }
        }
        public static void Warn(object message, Exception ex)
        {
            HandMessage(message, ex);
            if (log.IsWarnEnabled)
            {
                log.Warn(message, ex);
            }
        }
        public static void WarnFormat(string format, params object[] args)
        {
            HandMessage(format, args);
            if (log.IsWarnEnabled)
            {
                log.WarnFormat(format, args);
            }
        }
        */
        #endregion
    }
loghelper

 

7 全局异常处理

添加一个自定义过滤器

技术分享

    public class MyExceptionFileAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            //处理错误消息,将其跳转到一个页面
            LogHelper.Debug(filterContext.Exception.ToString());
            //页面跳转到错误页面
            // filterContext.HttpContext.Response.Redirect("/Error.cshtml");
        }
    }

  技术分享

注册过滤器

    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new MyExceptionFileAttribute());
        }
    }

完事

 

 

 

 

 

  

 

log4net配置+全局异常抓取防遗忘整理

标签:tac   csharp   hint   dna   自定义   目录   方式   tput   rri   

原文地址:http://www.cnblogs.com/stt-bky/p/7660318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!