简体   繁体   中英

NLog create log files based on static variable

How can I set NLog file name based on static variable in my application.

I have windows service that performs different tasks. Reads configuration file with task details. I would like to create log file based on given task name.

NOTE: class name will not work, since all the tasks call the same code.

NOTE: I am already using ${logger} variable as my current class. Since I need to know where I am as well.

-------------UPDATE--------------

Seems like this is not possible to do. Modified question: How to set variable values at run time? I am talking about this:

<variable name="logFileName" value="" />

Thank you.

You cannot, I believe. But you can use something like this:

In code:

static NLog.Logger loggerA = NLog.LogManager.GetLogger("nameA");
static NLog.Logger loggerB = NLog.LogManager.GetLogger("nameB");

void Something()
{
    loggerA.Error("Something");
}

void SomethingElse()
{
    loggerB.Error("SomethingElse");
}

NLog config:

<nlog ...>
    <targets>
        <target name="Error" xsi:type="AsyncWrapper">
            <target name="file" xsi:type="File" fileName="${basedir}/Logs/Error.txt">
                <layout ... />
            </target>
        </target>
    </targets>
    <!--other targets pointing to different files.-->
    <rules>
        <logger name="nameA" minlevel="Warn" writeTo="Error" />
        <logger name="nameB" minlevel="Trace" maxLevel="Info" writeTo="Log" />-->
        <logger name="*" minlevel="Trace" maxLevel="Info" writeTo="CommonLog" />
    </rules>
</nlog>

You can also use SomeNamespace.Component.* as name of a logger and than only logs from SomeNamespace.Component will be logged via it. In that case the logger would be obtained like this:

static NLog.Logger loggerA = NLog.LogManager.GetCurrentClassLogger();

Here is the documentation for Nlog: https://github.com/NLog/NLog/wiki/Tutorial

There is a way to edit NLog configuration programmatically: https://github.com/nlog/NLog/wiki/Configuration-API

The easy solution is to use NLog GlobalDiagnosticsContext:

<target name="file" xsi:type="File" fileName="${gdc:logFileName:whenEmpty=DefaultApp}.txt">

Then you can override it like this:

NLog.GlobalDiagnosticsContext.Set("logFileName", "HelloApp");

See also: https://github.com/nlog/nlog/wiki/Gdc-Layout-Renderer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM