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="Log\info.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="Log\warn.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="Log\error.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)]

Chobits
7.4k 声望171 粉丝

保卫骡博 Chobits#3780


引用和评论

0 条评论