。Net core 2.2中使用Nlog的特定日志到特定文件

问题描述 投票:0回答:2

我已经在.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");
                ...
            }
        }
    }
}

MY 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);
            }
        }
    }
}
c# asp.net-core-webapi nlog asp.net-core-2.2 nlog-configuration
2个回答
0
投票

规则从上至下匹配。所以minlevel = info也会匹配错误等。

这里的简单解决方案,使用level而不是minlevel

  <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="*" level="Info" writeTo="requestFile" />  
        <logger name="*" level="Warn"  writeTo="warnFile" />  
        <logger name="*" level="Error"  writeTo="errorFile" />  
    </rules>

替代选项

另一种选择是使用final并在出现错误时首先进行匹配,然后发出警告等。

例如

  <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="Error" writeTo="errorFile" final="true” />
      <logger name="*" minLevel="Warn" writeTo="warnFile" final="true" />  
      <logger name="*" minLevel="Info" writeTo="requestFile" final="true" />
    </rules>

另请参阅https://github.com/NLog/NLog/wiki/Configuration-file#rules


0
投票

我建议您为请求记录器ApiLoggingMiddleware设置特殊的记录规则:

<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="*ApiLoggingMiddleware" minLevel="Info" writeTo="requestFile" />  
    <logger name="*" minLevel="Error"  writeTo="errorFile" final="true" />  
    <logger name="*" minLevel="Warn"  writeTo="warnFile" final="true" />  
</rules>  

然后requestFile目标将不会被其他Info-logging事件污染。

但是请确保ApiExceptionLoggingMiddlewareApiLoggingMiddleware没有共享相同的Logger名称。看起来ApiLoggingMiddleware执行了请求日志,因此避免重用/滥用其Logger名称(请参见loggerFactory.CreateLogger<ApiLoggingMiddleware>()

© www.soinside.com 2019 - 2024. All rights reserved.