Modify NLog configurations specified with Configuration API through NLog config file xml

718 Views Asked by At

I have a project which uses the below code to create a NLog instance.

 public FileTarget CreateNLogFileTarget(string layout, FileArchivePeriod archiveMode, int maxArchiveFiles, 
        bool keepFileOpen, bool enableConcurrentWrites, ArchiveNumberingMode archiveNumberingMode, string fileName)
    {
        FileTarget fileTarget = new FileTarget();
        fileTarget.Layout = layout;
        fileTarget.ArchiveEvery = archiveMode;
        fileTarget.MaxArchiveFiles = maxArchiveFiles;
        fileTarget.KeepFileOpen = keepFileOpen;
        fileTarget.ConcurrentWrites = enableConcurrentWrites;
        fileTarget.ArchiveNumbering = archiveNumberingMode;
        fileTarget.FileName = fileName;

        return fileTarget;
    }

    FileTarget infoLogFileTarget = CreateNLogFileTarget(@"${longdate} ${message}",
            FileArchivePeriod.Hour, 70, false, true, ArchiveNumberingMode.Rolling, "${basedir}/Logs/" + infoLogName + "/${shortdate}{#}.log");

I am using this project in another project and I need to use this NLog utility class to create my loggers. But I need to override these configurations. How can I override these configurations through the xml file? Any help would be much appreciated.

2

There are 2 best solutions below

4
Julian On

To use the FileTarget from CreateNLogFileTarget in your XML config, you should first find out the target name of the FileTarget it's probably in other parts of the code. Then you could use the target in your config:

<logger name='*' minlevel="Trace" writeTo='theTarget' />

0
Rolf Kristensen On

Maybe by using NLog-variables. Change your CreateNLogFileTarget to setup the parameters to get their value from NLog-variables.

Then on startup check if these NLog variables already exists in the loaded NLog-configuration. If not then they are set by the runtime, before calling CreateNLogFileTarget.

https://github.com/NLog/NLog/wiki/Configuration-file#variables