webapi日志記錄(TXT存儲)


記錄webapi日志我使用了兩種辦法,一種是存儲TXT的log文檔,但我發現使用使用了我接口的日志都會存儲到我電腦上。后面改用數據庫存儲log。數據庫存儲log信息這種方法個人比較推薦。之前花費了一些時間來寫TXT存儲還是想記錄下來。

 

轉載自:https://blog.csdn.net/lordwish/article/details/72353851

1、引用NLog類庫

打開項目的NuGet包管理器,搜索NLog,為項目添加程序包引用。

 

2、修改項目配置文件

在webAPI項目的Web.config中進行NLog的配置。首先在節點configuration>configSections下添加節點:

此處name必需為nlog,否則配置信息將不能被讀取。 然后在configuration節點下添加節點nlog:

這里定義了日志文件的保存路徑、命名格式以及日志記錄類型和監聽級別。

 注意:<configSections>必須要緊跟在<configuration>下方

<configuration>
   <configSections>
      <section name="nlog" type="NLog.Config.ConfigSectionHandler,NLog" />
    </configSections>

  <nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema">
    <targets>
      <target name="logfile" xsi:type="File" fileName="${basedir}/LogFile/${date:format=yyyy/MM/dd}-api.txt"/>
      <target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source="Api Services"/>
    </targets>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="logfile"/>
      <logger name="*" minlevel="Trace" writeTo="eventlog"/>
    </rules>    
  </nlog>
</configuration>
View Code

 3、創建日志及跟蹤類

創建日志跟蹤類AppLog,繼承於System.Web.Http.Tracing下的跟蹤編寫器接口ITraceWriter,用於日志生成和寫入:

using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Tracing;

namespace InsideMesAPI.Log
{
    public sealed class AppLog : ITraceWriter
    {
        //日志寫入
        private static readonly Logger AppLogger = LogManager.GetCurrentClassLogger();
        private static readonly Lazy<Dictionary<TraceLevel, Action<string>>> LoggingMap = new Lazy<Dictionary<TraceLevel, Action<string>>>(() => new Dictionary<TraceLevel, Action<string>>
        {
            {TraceLevel.Info,AppLogger.Info },
            {TraceLevel.Debug,AppLogger.Debug },
            {TraceLevel.Error,AppLogger.Error },
            {TraceLevel.Fatal,AppLogger.Fatal },
            {TraceLevel.Warn,AppLogger.Warn }
        });


        private Dictionary<TraceLevel, Action<string>> Logger
        {
            get { return LoggingMap.Value; }
        }
        /// <summary>
        /// 跟蹤編寫器接口實現
        /// </summary>
        /// <param name="request"></param>
        /// <param name="category"></param>
        /// <param name="level"></param>
        /// <param name="traceAction"></param>
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            if (level != TraceLevel.Off)//未禁用日志跟蹤
            {
                if (traceAction != null && traceAction.Target != null)
                {
                    category = category + Environment.NewLine + "Action Parameters : " + JsonConvert.SerializeObject(traceAction.Target);
                }
                var record = new TraceRecord(request, category, level);
                if (traceAction != null)
                {
                    traceAction(record);
                }
                //  traceAction?.Invoke(record);
                Log(record);
            }
            //throw new NotImplementedException();
        }
        /// <summary>
        /// 日志寫入
        /// </summary>
        /// <param name="record"></param>
        private void Log(TraceRecord record)
        {
            var message = new StringBuilder();

            /**************************運行日志****************************/

            if (!string.IsNullOrWhiteSpace(record.Message))
            {
                message.Append("").Append(record.Message + Environment.NewLine);
            }

            if (record.Request != null)
            {
                if (record.Request.Method != null)
                {
                    message.Append("Method : " + record.Request.Method + Environment.NewLine);
                }

                if (record.Request.RequestUri != null)
                {
                    message.Append("").Append("URL : " + record.Request.RequestUri + Environment.NewLine);
                }

                if (record.Request.Headers != null && record.Request.Headers.Contains("Token") && record.Request.Headers.GetValues("Token") != null && record.Request.Headers.GetValues("Token").FirstOrDefault() != null)
                {
                    message.Append("").Append("Token : " + record.Request.Headers.GetValues("Token").FirstOrDefault() + Environment.NewLine);
                }
            }

            if (!string.IsNullOrWhiteSpace(record.Category))
            {
                message.Append("").Append(record.Category);
            }

            //if (!string.IsNullOrWhiteSpace(record.Operator))
            //{
            //    message.Append(" ").Append(record.Operator).Append(" ").Append(record.Operation);
            //}

            //***************************異常日志***********************************//
            if (record.Exception != null && !string.IsNullOrWhiteSpace(record.Exception.GetBaseException().Message))
            {
                var exceptionType = record.Exception.GetType();
                message.Append(Environment.NewLine);
                message.Append("").Append("Error : " + record.Exception.GetBaseException().Message + Environment.NewLine);

            }


            //日志寫入本地文件
            Logger[record.Level](Convert.ToString(message) + Environment.NewLine);
        }
    }
}
View Code

 創建日志篩選器類LogFilterAttribute,繼承於System.Web.Http.Filters下的篩選器特性基類,用於定義日志內容:

using System;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Tracing;

namespace InsideMesAPI.Log
{
    public class LogFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            GlobalConfiguration.Configuration.Services.Replace(typeof(ITraceWriter), new AppLog());
            var trace = GlobalConfiguration.Configuration.Services.GetTraceWriter();
            //trace.Info(actionContext.Request, "Controller : " + actionContext.ControllerContext.ControllerDescriptor.ControllerType.FullName + Environment.NewLine + "Action : " + actionContext.ActionDescriptor.ActionName, "JSON", actionContext.ActionArguments);
            //base.OnActionExecuting(actionContext);
        }
    }
}
View Code

創建異常篩選器類AbnormalFilterAttribute,繼承於System.Web.Http.Filters下的異常篩選器類,用於異常信息的跟蹤篩選:

using System;
using System.ComponentModel.DataAnnotations;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;
using System.Web.Http.Tracing;


namespace InsideMesAPI.Log
{
    public class AbnormalFilterAttribute : System.Web.Http.Filters.ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            GlobalConfiguration.Configuration.Services.Replace(typeof(ITraceWriter), new AppLog());
            var trace = GlobalConfiguration.Configuration.Services.GetTraceWriter();
            trace.Error(actionExecutedContext.Request, "Controller : " + actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerType.FullName + Environment.NewLine + "Action : " + actionExecutedContext.ActionContext.ActionDescriptor.ActionName, actionExecutedContext.Exception);
            var exceptionType = actionExecutedContext.Exception.GetType();
            if (exceptionType == typeof(ValidationException))
            {
                var resp = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(actionExecutedContext.Exception.Message), ReasonPhrase = "ValidationException" };
                throw new HttpResponseException(resp);
            }
            else if (exceptionType == typeof(UnauthorizedAccessException))
            {
                throw new HttpResponseException(actionExecutedContext.Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            else
            {
                throw new HttpResponseException(actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError));
            }
            //base.OnException(actionExecutedContext);
        }
    }
}
View Code

 

4、應用配置

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            日志配置
            config.Filters.Add(new Log.LogFilterAttribute());
            config.Filters.Add(new Log.AbnormalFilterAttribute());
         }
     }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM