代码之家  ›  专栏  ›  技术社区  ›  x19

NLog文件的自定义文件名

  •  0
  • x19  · 技术社区  · 6 年前

    我想为NLog文件定制一个文件名。我该怎么做? 我想有一个文件名根据这个号码记录错误。

    public static class ExceptionMiddlewareExtensions
    {
        public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILoggerManager logger)
        {
            app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    context.Response.ContentType = "application/json";
    
                    var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
                    if (contextFeature != null)
                    {
                        //var RequestId = Activity.Current?.Id ?? System.Web.HttpContext.Current.TraceIdentifier; ??? I want to use this string as file name
                        logger.LogError($"Something went wrong: {contextFeature.Error}");
                        context.Response.Redirect("/Home/Error");
    
                        await context.Response.WriteAsync(new ErrorDetails()
                        {
                            StatusCode = context.Response.StatusCode,
                            Message = "Internal Server Error."
                        }.ToString());
                    }
                });
            });
        }
    }
    

    <?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="${basedir}\log\internal-nlog.txt">
    
      <!-- enable asp.net core layout renderers -->
      <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
      </extensions>
    
      <!-- the targets to write to -->
      <targets>
        <!-- write logs to file  -->
        <target xsi:type="File" name="allfile" fileName="${basedir}\log\all-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
    
        <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
        <target xsi:type="File" name="ownFile-web" fileName="${basedir}\log\feportal-${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="ownFile-web-splited" fileName="${basedir}\log\feportal-${level}-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
      </targets>
    
      <!-- rules to map from logger name to target -->
      <rules>
        <!--All logs, including from Microsoft-->
        <logger name="*" minlevel="Trace" writeTo="allfile" />
    
        <!--Skip non-critical Microsoft logs and so log only own logs-->
        <logger name="Microsoft.*" maxLevel="Info" final="true" />
        <!-- BlackHole without writeTo -->
        <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
        <logger name="*" minlevel="Trace" writeTo="ownFile-web-splited" />
      </rules>
    </nlog>
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Julian    6 年前

    实际上有多种方法,其中一种方法是使用事件属性和结构化日志记录(NLog 4.5+)

    logger.LogError("Something went wrong: {Error}. Id: {UniqueId}", contextFeature.Error, myUniqueId);
    

    在配置中:

    <target xsi:type="File" 
            name="file1" 
            fileName="${basedir}\log\error-{event-properties:UniqueId}.log"
            ... />