Настраиваемое имя файла для файла NLog - PullRequest
0 голосов
/ 06 февраля 2019

Я хочу иметь собственное имя для файла 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 голосов
/ 09 февраля 2019

Действительно, существует несколько способов, один из вариантов - использовать свойства событий и структурированное ведение журнала (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"
        ... />

См. Также

...