NLog文件的自定义文件名

时间:2019-02-06 08:32:57

标签: c# asp.net-core error-handling asp.net-core-2.0 nlog

我想要一个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());
                }
            });
        });
    }
}

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="${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 个答案:

答案 0 :(得分:0)

确实有多种方法,一种选择是使用事件属性和结构化日志记录(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"
        ... />

另请参见