Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# NLog custom delimiter in programmatic configuration

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.

like image 780
user3079834 Avatar asked Dec 11 '25 19:12

user3079834


2 Answers

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

like image 98
Julian Avatar answered Dec 15 '25 16:12

Julian


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.

like image 34
Athanasios Kataras Avatar answered Dec 15 '25 15:12

Athanasios Kataras



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!