记录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>
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);
}
}
}
创建日志筛选器类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);
}
}
}
创建异常筛选器类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);
}
}
}
4、应用配置

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
日志配置
config.Filters.Add(new Log.LogFilterAttribute());
config.Filters.Add(new Log.AbnormalFilterAttribute());
}
}
来源:https://www.cnblogs.com/my2020/archive/2020/03/10/12457872.html
