NLog rename old file changing the original file name

I’m working with Nlog in an Asp.net framework application in a lan enviroment.
I have 10 different clients that use the application. My goal is to have different log file, one for each client. My Nlog configuration is:

<target name="LogFile"
    xsi:type="File"
    fileName="D:logs${var:idClient}.txt"
    keepFileOpen="true"
    archiveFileName="D:logsOld${var:idClient}_{#}.txt"
    archiveDateFormat="yyyyMMdd"
    archiveNumbering="Date"
    archiveEvery="Day"
    layout="${var:idClient}|${longdate}|${level:uppercase=true}|${callsite:fileName=false:includeSourcePath=false}|${message}"/>
</targets>

In the Global.asax:

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
        HttpContext context = HttpContext.Current;

        string idClient= string.Empty;
        if (context.Session == null || context.Session["ClientId"] == null ||
            string.IsNullOrEmpty(context.Session["ClientId"].ToString()))
            idClient= "Client ID Default";
        else
            idClient= System.Web.HttpContext.Current.Session["ClientId"]?.ToString();

        NLog.LogManager.Configuration.Variables["idClient"] = idClient;
}

My problem is that the old file name doesn’t have the same client id of the original log file. How can I mantain the same client id and add only the data?

Thanks.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

NLog config variables are global for the entire application. It is not a good idea to modify them for every request, unless you promise to only have a single request at a time.

Instead consider adding NLog.Web-nuget-package to your project and change your filetarget to use this FileName-layout:

    <extensions>
      <add assembly="NLog.Web"/>
    </extensions>
    <targets>
      <target name="LogFile" xsi:type="File"
        fileName="D:logs${aspnet-session:ClientId:whenEmpty=DefaultClientId}.txt" />
    </targets>

See also https://github.com/NLog/NLog/wiki/AspNetSession-layout-renderer


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x