• 00
  • :
  • 00
  • :
  • 00

ASP.NET Web API 记录请求响应数据到日志的一个方法

log4net配置:

添加LoggerHelper.cs

   public class LoggerHelper
    {
        static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
        static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
        static readonly log4net.ILog logmonitor = log4net.LogManager.GetLogger("logmonitor");

        /// <summary>
        /// 记录异常日志
        /// </summary>
        /// <param name="ErrorMsg"></param>
        /// <param name="ex"></param>
        public static void Error(string ErrorMsg, Exception ex = null)
        {
            if (ex != null)
            {
                logerror.Error(ErrorMsg, ex);
            }
            else
            {
                logerror.Error(ErrorMsg);
            }
        }

        /// <summary>
        /// 记录消息日志
        /// </summary>
        /// <param name="Msg"></param>
        public static void Info(string Msg)
        {
            loginfo.Info(Msg);
        }

        /// <summary>
        /// 记录监控日志
        /// </summary>
        /// <param name="Msg"></param>
        public static void Monitor(string Msg)
        {
            logmonitor.Info(Msg);
        }
    }

添加log4net配置文件log4net.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
  <log4net>
    <!--错误日志-->
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="log\\LogError\\"/>
      <appendToFile value="true"/>
      <rollingStyle value="Date"/>
      <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.txt'"/>
      <staticLogFileName value="false"/>
      <param name="MaxSizeRollBackups" value="100"/>
      <layout type="log4net.Layout.PatternLayout">
        <!--每条日志末尾的文字说明-->
        <!--输出格式-->
        <!--样例:2008-03-26 13:42:32,111 [10] INFO  Log4NetDemo.MainClass [(null)] - info-->
        <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别:  %-5level %n错误描述:%message%newline %n"/>
      </layout>
    </appender>
    <!--Info日志-->
    <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="Log\\LogInfo\\" />
      <param name="AppendToFile" value="true" />
      <param name="MaxFileSize" value="10240" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="StaticLogFileName" value="false" />
      <param name="DatePattern" value="yyyy\\yyyyMM\\yyyyMMdd'.txt'" />
      <param name="RollingStyle" value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别:  %-5level %n日志描述:%message%newline %n"/>
      </layout>
    </appender>

    <!--监控日志-->
    <appender name="MonitorAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="Log\\LogMonitor\\" />
      <param name="AppendToFile" value="true" />
      <param name="MaxFileSize" value="10240" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="StaticLogFileName" value="false" />
      <param name="DatePattern" value="yyyy\\yyyyMM\\yyyyMMdd'.txt'" />
      <param name="RollingStyle" value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别:  %-5level %n跟踪描述:%message%newline %n"/>
      </layout>
    </appender>
    <!--Error日志-->
    <logger name="logerror">
      <level value="ERROR" />
      <appender-ref ref="RollingLogFileAppender" />
    </logger>
    <!--Info日志-->
    <logger name="loginfo">
      <level value="INFO" />
      <appender-ref ref="InfoAppender" />
    </logger>
    <!--监控日志-->
    <logger name="logmonitor">
      <level value="Monitor" />
      <appender-ref ref="MonitorAppender" />
    </logger>
  </log4net>
  <!--<system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>-->

</configuration>

将配置文件log4net.config应用到程序集:

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

直接调用LoggerHelper.Info(msg);就可以了

生成的目录结构:

 

 

WebAPI 日志记录:

添加一个类继承自DelegatingHandler

 public class CustomMessageHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            //return base.SendAsync(request, cancellationToken);
            //记录请求内容
            if (request.Content != null)
            {
                string msg = string.Format("请求Content:{0}", request.Content.ReadAsStringAsync().Result);
                LoggerHelper.Info(msg);
            }
            //发送HTTP请求到内部处理程序,在异步处理完成后记录相应内容
            return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((task) =>
            {
                // 记录响应内容
                string msg = string.Format("响应Content:{0}", task.Result.Content.ReadAsStringAsync().Result);
                LoggerHelper.Info(msg);
                return task.Result;
            });
        }
    }

 

 然后修改全局,Global.asax.cs,添加监控类

 参考地址:http://blog.bossma.cn/dotnet/asp-net-web-api-log-request-response/

posted @ 2017-11-17 16:17  Garson_Zhang  阅读(3433)  评论(1编辑  收藏  举报