1

To fully use advantages of MDLC in NLog I'm trying to set MDLC params at the init method of all objects I need to identify later when debugging by logs.

For example, there is an A class with some Foo() method where I have something like logger.Debug('Foo method started'). There are some objects executing Foo() method async, so I have some MDLC params for this task, for example, MappedDiagnosticsLogicalContext.Set("A_Id", this.id);.

And there is an B class with some Bar() method which logs logger.Debug('Bar method started'). And again I need to identify B objects or just need some same params every log call, so I have MappedDiagnosticsLogicalContext.Set("B_Id", this.id);.

And there is no Layout properrty in <Logger/>. Only in <Target/>. So I see 3 ways to include this MDLC params based on logger class:

  1. Chaining when constructions:

    <variable name="optional" value="${aParams}${when:when=equals('${logger}','App.B'):inner=|${mdlc:item=B_id}}"/>
    
    <target layout="${optional}" 
    fileName="logs.txt"
    name="f"
    xsi:type="File"/>
    
  2. To have multiple targets (one for each logger) and with the same fileName. Not sure it is really legal but as I remember I've seen that somewhere.

    <target layout="${mdlc:item=A_id}"
        fileName="logs.txt"
        name="f"
        xsi:type="File"/>
    
    <target layout="${mdlc:item=B_id}"
        fileName="logs.txt"
        name="f"
        xsi:type="File"/>
    
  3. To have shared MDLC param like MappedDiagnosticsLogicalContext.Set("Param", this.id);. in A class and MappedDiagnosticsLogicalContext.Set("Param", this.id); in B class.

    <target layout="${mdlc:item=Param}"
        fileName="logs.txt"
        name="f"
        xsi:type="File"/>
    

The third one looks most easy to implement but if this is preferrable way I don't see any reasons to have dictionary and use only one key everywhere. So may be there is some easier way to do that or which is preferred?

Tony Young
  • 45
  • 1
  • 7

1 Answers1

1

Option 3 is from a performance view the fastest, as NLog could print without checking the condition. Also the config is easier to read.

Option 2 is not supported.

Option 1 could be more flexible, but a bit slower.

NB: I'm not sure of the MDLC is best choice here. I think event properties is also an option.

Julian
  • 33,915
  • 22
  • 119
  • 174