Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NLog dynamically change filename using NLog.config

How to dynamically change the FileName using a variable from C#? My idea is to create a log file like Log_<UserId_From_DB>_${date:format=yyyy-MM-dd}.log. Any ideas?

like image 380
gjfonte Avatar asked May 19 '16 15:05

gjfonte


People also ask

How to get configuration values from nlog config file?

Try use custom layout renderer: NLog config file to get configuration setting values from a web.config As possible workaround try add your own LayoutRenderer: stackoverflow.com/questions/7107499/… Tony's solution doesn't seem to work if you use NLog Async ( <targets async="true"> ).

How do I use a custom file name in nlog events?

logEvent.Properties ["CustomFileName"] = "mycustomfilename"; The interesting thing here is that in your NLog configuration, you can use this custom property in any field that the Nlog documentation refers to as a "Layout" value. You use $ {event-properties:item=CustomFileName} in the layout to access the property. For example:

Is it safe to change the nlog variable at runtime?

Please avoid modifying NLog Variables at runtime (See previous answer below). They should be seen as readonly, because they are not threadsafe. NLog Variables will also be affected if LoggingConfiguration is reloaded. If the value is set again, the filename will automatically changed. Show activity on this post.

What Wildcards are allowed in nlog configuration files?

Since NLog 4.4.2, wildcards ( *) are allowed. E.g. <include file="nlog-*.config"/> A larger example can be found here: XML config <include /> example In the configuration file some characters needs to be escaped. Because it XML file, the < and > brackets should be escaped with < and >. This also holds for the attribute values, like a condition.


1 Answers

Another option is to use the Global Diagnostic Context - $(GDC):

Set the value in C#

GlobalDiagnosticsContext.Set("UserId_From_DB","42");

In the config (nlog.config):

<target type="file" filename="Log_${gdc:item=UserId_From_DB}_${date:format=yyyy-MM-dd}.log" ..>

Please avoid modifying NLog Variables at runtime (See previous answer below). They should be seen as readonly, because they are not threadsafe. NLog Variables will also be affected if LoggingConfiguration is reloaded.

Previous answer with NLog Variables:

Set the value in C#

LogManager.Configuration.Variables["UserId_From_DB"] = "42";

In the config (nlog.config):

<target type="file" filename="Log_${var:UserId_From_DB}_${date:format=yyyy-MM-dd}.log" ..>

If the value is set again, the filename will automatically changed.

like image 200
Julian Avatar answered Oct 17 '22 06:10

Julian