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?
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"> ).
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:
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With