1

I'm tasked with a WPF app & have chosen NLog for our logging.

I note answers here and here I would like to do something similar but with .net Desktop & with more control.

I would like to set a guid once at app start and each log entry (at any level) have this guid included automatically, so I can search on that guid. Creating a new guid when the user logs in.

Going further it would actually be good knowledge to know if I can programmatically add any variables that get included with every Log I make, so I dont have to add them to each and every Log.AnyLevel, an example output:

DateTime | LoginID | SessionGuid | MyMessage  

to get this output I like to only do:

logger.Trace("MyMessage")

LoginID & SessionGuid being set either when App starts or I instantiate a ViewModel or the User Logs in.

I note at present I can do this per log with

LogEventInfo

How can I add a variable once (from code) and have it always included?

Julian
  • 33,915
  • 22
  • 119
  • 174
tinmac
  • 2,357
  • 3
  • 25
  • 41

1 Answers1

2

You can setup a NLog GDC variable:

GlobalDiagnosticsContext.Set("AppGuid",Guid.NewGuid().ToString());

And then reference that in your layouts:

${gdc:item=AppGuid}

See also https://github.com/NLog/NLog/wiki/Gdc-layout-renderer

Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70
  • Oh right, I have looked at GDC but was under the impression it was obsolete (from https://stackoverflow.com/a/17767739/425357) – tinmac Feb 21 '19 at 17:12
  • GDC is usually for global data that stays pretty much the same for the lifetime of the application. LogEvent-properties should be used for context-specific or logevent-specific variables. – Rolf Kristensen Feb 21 '19 at 18:20
  • Thank you, appreciate your time. – tinmac Feb 21 '19 at 18:31
  • 1
    Happy to help. Have modified the stackoverflow answer you referred to with more correct details. – Rolf Kristensen Feb 21 '19 at 18:42