我已经在 .net core 2.2 web api 中成功配置了 NLog。但我想通过日志记录来实现规范。如何实现如下:
- 应记录警告以警告特定文件
- 应将错误记录到错误特定文件
- 当我记录请求/响应时,该文件应该只包含我的请求
但是目前使用请求日志,该文件还将错误/警告日志保存在同一文件中,并且也在错误/警告特定日志文件中。如何将日志隔离在分类文件中,以便特定日志仅存储在该文件中,而不会同时存储在其他文件中?
我的 nlog.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="info" internalLogFile="internalLog.txt">
<extensions>
<add assembly="NLog.Web.AspNetCore" />
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write to file -->
<target xsi:type="File"
name="allFile"
fileName="${var:customDir}\logs\AllLog\${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
<!-- another file log. Uses some ASP.NET core renderers -->
<target xsi:type="File"
name="requestFile"
fileName="${var:customDir}\logs\RequestTrace\${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
<target xsi:type="File" name="warnFile" fileName="${var:customDir}\logs\Warnings\Warn_${shortdate}.log" />
<target xsi:type="File" name="errorFile" fileName="${var:customDir}\logs\Errors\Error_${shortdate}.log" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<logger name="*" minLevel="Trace" writeTo="allFile" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<!--<logger name="Microsoft.*" maxLevel="Info" final="true" />-->
<logger name="*" minLevel="Info" writeTo="requestFile" />
<logger name="*" minLevel="Warn" writeTo="warnFile" />
<logger name="*" minLevel="Error" writeTo="errorFile" />
</rules>
</nlog>
我的启动文件
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(config =>
{
config.Filters.Add(new ApiLoggingMiddleware());
config.Filters.Add(new ApiExceptionLoggingMiddleware());
}
).SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressInferBindingSourcesForParameters = true;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseDeveloperExceptionPage();
app.UseAuthentication();
//app.UseMiddleware<ApiLoggingMiddleware>();
LogManager.Configuration.Variables["customDir"] = Directory.GetCurrentDirectory();
}
}
}
我的 apilogginmiddleware.cs 文件
public class ApiLoggingMiddleware : TypeFilterAttribute
{
public ApiLoggingMiddleware() : base(typeof(AutoLogActionFilterImpl))
{
}
private class AutoLogActionFilterImpl : IActionFilter
{
private readonly ILogger _logger;
public AutoLogActionFilterImpl(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<ApiLoggingMiddleware>();
}
public void OnActionExecuting(ActionExecutingContext context)
{
// perform some business logic work
}
public void OnActionExecuted(ActionExecutedContext context)
{
...
_logger.LogInformation("Log request data");
...
}
}
}
}
我的 apiexceptionloggingmiddleware.cs 文件
public class ApiExceptionLoggingMiddleware : TypeFilterAttribute
{
public ApiExceptionLoggingMiddleware() : base(typeof(AutoLogExceptionImpl))
{
}
private class AutoLogExceptionImpl : IExceptionFilter
{
private readonly ILogger _logger;
public AutoLogExceptionImpl(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<ApiLoggingMiddleware>();
}
public void OnException(ExceptionContext context)
{
_logger.LogError("Errors : " + context.Exception
+ Environment.NewLine + Environment.NewLine);
}
}
}
}