Logging Unique Request IDs in text file NLog - To differentiate between requests

StackOverflow https://stackoverflow.com/questions/20088847

  •  02-08-2022
  •  | 
  •  

سؤال

I am using NLog logging mechanism in my application. The problem I face is when concurrent requests hit the application logging is done asynchronously and I am not able to identify which line belongs to which request. Is there a way in NLog to set the configuration to NLog itself logging a unique Request ID for each request ?

<?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">  
<targets>    
<!-- add your targets here -->
<target xsi:type="File" name="file"    fileName="E:\IBELogs\AirAvailability\AirAvailability.log" layout="${longdate}        ${uppercase:${level}} ${message}" />    
</targets>
<rules>
<!-- add your logging rules here --> 
<logger name="*" minlevel="Trace" writeTo="file" />    
</rules>
</nlog>
هل كانت مفيدة؟

المحلول 2

You will have to generate your unique ID yourself. Then you can set the unique ID into the MDC and set the appropriate layout format that outputs your unique from MDC into the log.

نصائح أخرى

In NLog 4.1 ${activityid} was introduced, see here. I cannot say MSDN documentation is clear enough about its value, but so far, this is doing the trick for us, since every request in our webAPI application gets assigned a unique GUID and it is preserved through the entire request as we see the same value in several Nlog operations in the same request.

We faced a similar problem and we used the thread Id to identify the lines in the logfile. Therefore specify the layout like the following:

<target ... layout="threadID: ${threadid} ${message}"/>

If the concurrent requests differ in nature it may be a good idea to create multiple loggers, one for each request type. Then you can do something like this:

<target ... layout="logger: ${logger} ${message}"/>

I hope this helps.

Step 1. Initialize Trace.CorrelationManager.ActivityId in the Global.asax

    protected void Application_BeginRequest()
    {
        Trace.CorrelationManager.ActivityId = Guid.NewGuid();
    }

Step 2. Add ${activiryid} in the NLog.config

layout="${longdate}|${activityid}|${threadid}|${level:uppercase=true}|${callsite}|Line-${callsite-linenumber}|${message}"

Then the activityid in the log file can be treated as the request id.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top