mhenry1384
mhenry1384

Reputation: 7688

switch to "trace" log level, but only for current web request (nLog)

I would like the ability to turn on trace-level logging in nLog, on production, but only for the current web request.

In other words, I'd like to be able to do something like...

http://mywebsite.com?logeverything=true

... which would do trace-level logging, but only for that web request, not the hundreds of other requests that are happening at the same time. I'd also like the logs for that request to go to a different file than where the rest of the logging is going to. An acceptable alternative to a query string would be to turn on the trace-level logging but only if the web request is local.

I could write my own Logger class and override the nLog log methods to do something along these lines, but my web project uses a number of different assemblies and and switching all the projects to use a new logger class would be something of a pain.

Anyone doing anything like this?

Upvotes: 0

Views: 415

Answers (1)

Julian
Julian

Reputation: 36790

This could be done without the need of wrappers.

  1. Install also NLog.Web (or in the case of ASP.NET Core: NLog.Web.AspNetCore nd follow the installation tutorial

  2. Create your trace logs in c#

  3. Write to session it's your request
  4. Filter your logs in the .config

    <logger name="*" writeTo="myFile">
       <filters>
         <when condition="${aspnet-session:Variable=myRequest} != 1" action="Ignore" />
      </filters>
    </logger> 
    
    • in this case I use the session, but you could also use ${aspnet-request-url} - but that makes the config a bit more complicated

Upvotes: 1

Related Questions