Ed Landau
Ed Landau

Reputation: 998

NLog: Adding database targets grammatically (using AddTarget)

Using multi-threaded C# with a .NET console app, I currently use NLog to log to a file and to a database. I write to several different log files depending on which "store" processes the transaction. I do this by adding file targets like this:

        var targetFileName = Path.Combine(Path.GetDirectoryName(fileName),
            string.Format("{0}-{1}{2}", Path.GetFileNameWithoutExtension(fileName), name, Path.GetExtension(fileName)));
        var target =
            new FileTarget
            {
                FileName = targetFileName,
                Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff}|${level}|${threadid}|${logger}|${event-properties:item=StoreID}|${message}${exception:format=tostring}"
            };

        //Add async wrapper here
        var asyncWrapper = new AsyncTargetWrapper
        {
            WrappedTarget = target,
            QueueLimit = 20000,
            OverflowAction = AsyncTargetWrapperOverflowAction.Discard
        };
        //Create rule
        var rule = new LoggingRule(name, LogLevel.Trace, asyncWrapper);
        LogManager.Configuration.LoggingRules.Add(rule);
        //Add target
        LogManager.Configuration.AddTarget(name, asyncWrapper);
        //Tell logmanager to reconfigure itself
        LogManager.ReconfigExistingLoggers();

I can then use LogManager.GetLogger(name) to retrieve the logger.

In my NLog.config, I also log to a database <target name="Database" xsi:type="Database">

I run my application and shut it down every day. Using file targets, I can easily create files every day by creating a new FileTarget.

Is there a way to do the same with a Database? It would of course need to be created somehow with some initialization code... but I don't see any documentation for adding anything but a "file" target.

Ideally I'd have a new database created every day (every time I run), with a filename representing what day it ran (much like I do above with a FileTarget).

Upvotes: 0

Views: 631

Answers (1)

Julian
Julian

Reputation: 36790

Everything in NLog could be configured from config file (nlog.config) and in code.

For this you need the DatabaseTarget (namespace NLog.Targets).

The names of the properties do match with the XML attributes, so the documentation is here: Database target.

Small example:

var config = new LoggingConfiguration();
config.AddRuleForAllLevels(new DatabaseTarget()
{
    ConnectionString = "MyConnectionString",
    CommandText = "INSERT .... ", //todo
    Parameters =
    {
        new DatabaseParameterInfo("@message", "${message}"),
        new DatabaseParameterInfo("@error", "${exception}"),
        new DatabaseParameterInfo("@date", "${date}"){ DbType = "DbType.Date"},
    }
});
LogManager.Configuration = config; // Apply config

Upvotes: 0

Related Questions