NLog Configuration API: Using Layouts stored in variables

守給你的承諾、 提交于 2020-01-14 14:31:07

问题


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.


回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/9635616/nlog-configuration-api-using-layouts-stored-in-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!