Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NLog Configuration API: Using Layouts stored in variables

My app creates a log for the application itself, so record when it was activated, and what happened at an application level.

The application is centered around 'profiles' - the user loads a profile which tells the application where/when/what/how. So I also want to create a log for each profile, to record the progress each time the profile is run.

No problems so far... except that I want the profile log to be stored alongside the profile itself, so this means I need to configure NLog dynamically, so I can tell it the fileTarget path at runtime.

However, I was also wanting to store the standard layouts I want to use, as variables in NLog.config; this seems to be a common enough approach from what I have read.

However, at the following line

fileTarget.Layout = "${myLayout}"

...I get an ArgumentException:

LayoutRenderer cannot be found: 'myLayout'

At the moment, my layout variable is simply:

<variable name="myLayout" value="${message}" />

Is it a case that you can't use variables to specify layout through the API? I would be surprised if that was the case. Or have I gone wrong somewhere?

The solution is simple enough - I can populate fileTarget.Layout with a manually-specified layout, but nevertheless, I'm keen to find out if Plan A could work.

like image 310
CJM Avatar asked Mar 18 '26 15:03

CJM


2 Answers

I got the latest source code (NLog 3.2.0.0) and figured out a solution that is supported without any changes to NLog. The code below gets the value of a variable. I assume it can also be written to, but I did not try that because I don't need that functionality. That answers the question. The last line evaluates the text in the variable to render any layout renderers that it contains.

var config = (NLog.Config.XmlLoggingConfiguration)LogManager.Configuration;
string dir = config.Variables["logDirectory"];
dir = NLog.Layouts.SimpleLayout.Evaluate(dir);
like image 131
MarkR Avatar answered Mar 21 '26 06:03

MarkR


It's not possible if you're using a compiled binary from NLog's site, mainly because NLog doesn't expose an API for accessing <variable> elements.

You could suggest the author to add this ability, OR if you're really keen about having this ability, then download and modify the source code. private string ExpandVariables(string input) in file XmlLoggingConfiguration.cs is what you'll need to expose.

Good luck.

like image 24
AVIDeveloper Avatar answered Mar 21 '26 05:03

AVIDeveloper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!