[Work] for small NLog custom LayoutRenderer

Long story short

  The foregoing " anatomical HttpClientFactory, free to expand HttpMessageHandler " mainly want to talk about how to extend HttpMessageHandler , example shows TraceId to log in every Http request, the

Now to complete the small after-school job: TraceId will be displayed on the Nlog LayoutRenderer.

The re-implement a smooth and simple LoggingHttpMessageHandler, and added to NLog LayoutRenderer.

 What is the Layout Renderer?

 Nlog particular field appear on the log, to facilitate retrieval and classification.

Brainstorming

Give from the definition Renderer, definition named eqid custom Renderer of

# 截取自 nlog.config配置文件
<variable name="format1" value="${date:format=yy/MM/dd HH\:mm\:ss} [${level}].[${logger}].[${threadid}}].[${aspnet-request-url:IncludeScheme=false:IncludeHost=false}].[${eqid}]${newline}${message} ${exception:format=tostring}" />

<target name="bce-request"
           xsi:type="File"
           layout="${format1}"
           fileName="${logDir}/bce-request.log"
           encoding="utf-8"/>

 

-------------------------------1----------------------------

 Nlog add custom LayOutRenderer,  https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer

  There are simple ways of lambda, where we take a slightly flexible custom class way:

 [LayoutRenderer("eqid")]
    public class EqidLayoutRenderer : LayoutRenderer
    {
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            builder.Append(logEvent.Properties["EventId_Name"].ToString());
        }
    }

The key point is to achieve a method LayoutRenderer abstract Append, formed by the key parameters logevent writing Logging.

Causes of eqid renderer values ​​from step 2 in EventId.Name

---------------------------------2-----------------------------

Combined with, we, are written in the value of the Renderer of the property at the time written to the log:

public class AttachTraceIdScopeHttpMessageHandler : DelegatingHandler
    {
        private  readonly ILogger _logger;

        public AttachTraceIdScopeHttpMessageHandler(ILogger logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var stopwatch = Stopwatch.StartNew();
            var eventName = request.RequestUri.LocalPath.Split('/').LastOrDefault();

            _logger.Log(LogLevel.Information, new EventId(100, eventName),
                $"Start processing HTTP request {request.RequestUri} {request.Method}");
            var response = await base.SendAsync(request, cancellationToken);
            stopwatch.Stop();
            _logger.Log(LogLevel.Information, new EventId(101, eventName),
                $"End processing HTTP request after {stopwatch.Elapsed.TotalMilliseconds}ms - {response.StatusCode}");
            return response;
        }
    }

Name property EventId the last to be found in the EventLogInfo nlog for Property [EventId_Name], so we have more operations.

The manner described above, is added to CustomHttpMessageHandlerFilter, and registered as IHttpMessageHandlerFilter achieve.

 

--------------------------------3------------------------

Accordance with the requirements of the document, as soon as possible to register a custom Nlog LayoutRenderer,

So I signed up for the Renderer when the main function starts, the registered name is TraceId

public static void Main(string[] args)
{
            LayoutRenderer.Register<EqidLayoutRenderer>("eqid");
......
}

The final output is as follows:

19/12/07 00:35:42 [Info].[System.Net.Http.HttpClient.bce-request.LogicalHandler].[19}].[].[125aa91f0011426c000000045dea5ea0]
Start processing HTTP request http://localhost:5000/v1/eqid/125aa91f0011426c000000045dea5ea0 GET 
19/12/07 00:35:44 [Info].[System.Net.Http.HttpClient.bce-request.LogicalHandler].[5}].[].[125aa91f0011426c000000045dea5ea0]
End processing HTTP request after 2178.9971ms - OK 

 

ok, run the examples in this article, be sure to see " anatomy HttpClientFactory, free to expand HttpMessageHandler " ideas, the main purpose of this paper is to explain the custom Nlog LayoutRenderer.

 

Guess you like

Origin www.cnblogs.com/JulianHuang/p/12000310.html