Search code examples
nlog

Can I use two different layouts in one target in NLog?


I have two layouts in nlog.config. once is Default layout and other one is ErrorLayout in which have additional properties. the problem is i want to add target and i want to use both layout for LogLevel.Error i have to use ErrorLayout and for the other levels i have to use DefaultLayout. i don't want to create two target because two targets creating two different file and store logs into it. but i want to both layout into one target. can I able to do that? How ? can anyone help me to do this ?

enter image description here


Solution

  • Another option is you use two targets, targeting the same file. If you don't enable keepfileopen, then this is also a good solution.

    For example:

    <nlog>
        <targets>
            <target type="file" name="erp" layout="${message}" fileName="log-${shortdate}.log" />
            <target type="file" name="erp-error" layout="${message} ${exception:format=tostring}" fileName="log-${shortdate}.log" />
        </targets>
    
        <rules>
            <logger name="*" minLevel="Error" writeTo="erp-error" final="true" /> <!-- after match events won't be processed futher due to the final attribute -->
            <logger name="*" minLevel="Debug" writeTo="erp" />
        </rules>
    </nlog>