Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NLog how can I make my modules log to their own unique log file

Tags:

c#

logging

nlog

I'm trying to change an application so that when it creates an instance of a module (a class defined in another assembly) it can provide the necessary information to the module so that it can create it's own logger based off the configuration of the service application loading it.

When I first started working on this the most logical solution to me was to create a log configuration file with a custom parameter that is used to determine the file name.

<variable name="module" value="Service"/>

<targets>
   <target name="logFile" xsi:type="File" fileName="${basedir}Logs/${var:module}.txt"
            layout="${time} ${uppercase:${level}} ${var:module} ${logger} ${message}" />
</targets>

Then I store the LoggingConfiguration so every time a module is loaded I create a new LogFactory based off of the configuration, change the custom variable value, and inject it as a dependency on the module for it to use for creating its own loggers.

The problem I keep encountering, even when I write a complex method to attempt to clone the LoggingConfiguration, is it always results in everything, service included, logging to the specifications of the last LogFactory created.

I feel like I'm missing something and could really use some help either figuring out how I can make this solution work or any suggestions for a better idea of how I might achieve the same goal of a unique log file per module.

like image 560
Thermonuclear Avatar asked Sep 11 '25 21:09

Thermonuclear


1 Answers

You could also provide a common interface for all modules. This interface also includes the ability acquire a custom Logger-object that wraps an NLog Logger.

The custom Logger-object then injects the module name into LogEventInfo.Properties. Maybe extracted from:

System.Reflection.Assembly.GetCallingAssembly().Name

Then you can use ${event-properties:item=ModuleName} in the filename.

See also https://github.com/NLog/NLog/wiki/EventProperties-Layout-Renderer

like image 123
Rolf Kristensen Avatar answered Sep 13 '25 12:09

Rolf Kristensen