I'm using NLog in VS2019 and when setting up the logger programmatic (no external nlog configuration file) before first use, I define the loggers there like
var logConsole = new NLog.Targets.ColoredConsoleTarget()
{
Name = "logconsole",
Layout = "${longdate}|${level:upperCase=true}|${message}"
};
config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, logConsole));
Currently I have the delimiter | hardcoded there.
How can I make the delimiter variable? Defining a string delim = "|" and then setting Layout to Layout = "${longdate}${delim}${level:upperCase=true}${delim}${message}" does not work here.
You could use a context construction for that in NLog, e.g. the GlobalDiagnosticsContext.
Example:
var logConsole = new NLog.Targets.ColoredConsoleTarget()
{
Name = "logconsole",
Layout = "${longdate}${gdc:item=delimiter}${level:upperCase=true}${gdc:item=delimiter}${message}"
};
config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, logConsole));
And set in your code:
GlobalDiagnosticsContext.Set("delimiter", "|");
You could change the delimiter then in code in other places.
The GlobalDiagnosticsContext is global for the whole application. If you need a more limited scope, that's also possible! See NLog - Context
Try like this:
string delim = "|";
Layout = "${longdate}" +delim+"${level:upperCase=true}"+delim+"${message}";
The ${} syntax, denotes what will be replaced. So to concatenate with a string variable, you need to add the characters with string concatenation.
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