asp.net log4net

Chobits發表於2016-09-07

web.config

  <system.webServer>
    ...
    <staticContent>
      <mimeMap fileExtension=".log" mimeType="text/plain;charset=GBK" />
    </staticContent>
  </system.webServer>
  <appSettings>
    ...
    <add key="log4net" value="log4net.config" />
  </appSettings>

log4net.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configuration>
    <configSections>
      <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=1B44E1D426115821" />
    </configSections>
    <log4net>
      <root>
        <level value="DEBUG"/>
        <!--根據log級別記錄到不同的日誌檔案-->
        <appender-ref ref="InfoLog" />
        <appender-ref ref="WarnLog" />
        <appender-ref ref="ErrorLog" />
      </root>
      <appender name="InfoLog" type="log4net.Appender.RollingFileAppender">
        <!--INFO、DEBUG級別的日誌檔案路徑,根據自己的需要修改-->
        <file value="Loginfo.log" />
        <appendToFile value="true" />
        <rollingStyle value="Date" />
        <datePattern value=".yyyyMMdd" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
        </layout>
        <filter type="log4net.Filter.LevelRangeFilter">
          <levelMin value="DEBUG" />
          <levelMax value="INFO" />
        </filter>
      </appender>
      <appender name="WarnLog" type="log4net.Appender.RollingFileAppender">
        <!--WARN級別的日誌檔案路徑,根據自己的需要修改-->
        <file value="Logwarn.log" />
        <appendToFile value="true" />
        <rollingStyle value="Date" />
        <datePattern value=".yyyyMMdd" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
        </layout>
        <filter type="log4net.Filter.LevelRangeFilter">
          <levelMin value="WARN" />
          <levelMax value="WARN" />
        </filter>
      </appender>
      <appender name="ErrorLog" type="log4net.Appender.RollingFileAppender">
        <!--ERROR級別的日誌檔案路徑,根據自己的需要修改-->
        <file value="Logerror.log" />
        <appendToFile value="true" />
        <rollingStyle value="Date" />
        <datePattern value=".yyyyMMdd" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
        </layout>
        <filter type="log4net.Filter.LevelRangeFilter">
          <levelMin value="ERROR" />
          <levelMax value="ERROR" />
        </filter>
      </appender>
    </log4net>
  </configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
</configuration>

LogService

    public static class LogService
    {
        public static readonly ILog logger = null;
        static readonly string path = System.Configuration.ConfigurationManager.AppSettings["log4net"];

        static LogService()
        {
            string fileName = HttpContext.Current.Server.MapPath("~").TrimEnd(`\`) + path;
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
            log4net.Config.XmlConfigurator.ConfigureAndWatch(fileInfo);
            log4net.Config.XmlConfigurator.Configure();
            logger = LogManager.GetLogger("LogWritter");
        }

        public static void Warn(object message)
        {
            logger.Warn(message);
        }

        public static void Info(string message)
        {
            logger.Info(message);
        }

        public static void Error(string message)
        {
            logger.Info(message);
        }

        public static void Error(Exception exception)
        {
            logger.Error(FlattenException(exception));
        }

        public static string FlattenException(Exception exception)
        {
            var stringBuilder = new StringBuilder();

            while (exception != null)
            {
                stringBuilder.AppendLine(exception.GetType().FullName);
                stringBuilder.AppendLine(exception.Message);
                stringBuilder.AppendLine(exception.StackTrace);

                exception = exception.InnerException;
            }

            return stringBuilder.ToString();
        }
    }

Global.asax

        protected void Application_Error(object sender, EventArgs e)
        {
            HttpServerUtility server = HttpContext.Current.Server;
            // ...  
            // Use HttpContext.Current to get a Web request processing helper  
            Exception exception = server.GetLastError();
            // Log an exception 
            LogService.Error(exception);

#if !DEBUG
            Server.ClearError();
            Response.Redirect("/error.html");
            Response.End();
#endif
        }

ExceptionHandling

    [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
    public class ExceptionHandlingAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// http://stackoverflow.com/questions/21580861/how-to-return-json-for-errors-outside-the-webapi-pipeline
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(HttpActionExecutedContext context)
        {
            // Log an exception 
            LogService.Error(context.Exception);

            ErrResponse err;

            if (context.Exception is BllException)
            {
                var bex = context.Exception as BllException;
                err = new ErrResponse(bex.ErrorCode, bex.ErrorMsg);
            }
            else
            {
                err = new ErrResponse(404, context.Exception.Message);
            }

            context.Response = context.Request.CreateResponse(HttpStatusCode.OK, err);

            base.OnException(context);
        }
    }

Global.asax

        protected void Application_Error(object sender, EventArgs e)
        {
            HttpServerUtility server = HttpContext.Current.Server;
            // ...  
            // Use HttpContext.Current to get a Web request processing helper  
            Exception exception = server.GetLastError();
            // Log an exception 
            LogService.Error(exception);

#if !DEBUG
            Server.ClearError();
            Response.Redirect("/error.html");
            Response.End();
#endif
        }

AssemblyInfo.cs

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

相關文章