Customers who sign-up prior to 30/06/2024 get unlimited access to free features, newer features (with some restrictions), but for free for at least 1 year.Sign up now!
.Net C#

Programatically configuring NLog in C#

Some people for various reasons might prefer programatically configuring NLog. Some use cases are for example, may be you don’t want to store sensitive information in nlog.config file. Some of the targets that require sensitive information in the config file are (Not an exhaustive list):

You might want to store the sensitive information somewhere else in an encrypted format. Then you might decrypt the password and programmatically configure the logger. Here is some code sample on how to configure such loggers.

var logConfig = new LoggingConfiguration();

var fileTarget = new FileTarget
        FileName=typeof(Program).FullName + ".log"

fileTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger}:${message};${exception}";

var fileRule = new LoggingRule("*", LogLevel.Debug, fileTarget);
logConfig.AddTarget("logfile", fileTarget);

var dbTarget = new DatabaseTarget();

dbTarget.ConnectionString = YourSecureMethodForDecryptingAndObtainingConnectionString();

dbTarget.CommandText = @"INSERT INTO [Log] (Date, Thread, Level, Logger, Message, Exception) VALUES (GETDATE(), @thread, @level, @logger, @message, @exception)";

dbTarget.Parameters.Add(new DatabaseParameterInfo("@thread", new NLog.Layouts.SimpleLayout("${threadid}")));

logConfig.AddTarget("database", dbTarget);
var dbRule = new LoggingRule("*", LogLevel.Debug, dbTarget);

LogManager.Configuration = logConfig;

In the above sample code, we have looked into how to add multiple types of targets – File and DB. How to set the layout for the FileTarget. How to configure logging rules and finally how to assign the programmatic config.

An interesting target is the Memory target, allows writing log messages to an ArrayList in memory for programmatic retrieval. Great for unit testing.

There are some code samples in the above mentioned link for Memory target.