Log generation with NLog?

I am using NLog, and for each client logged into the system I would like to create a behavior for log generation as follows:

[nome-cliente-1]-[dataAtual].txt

[nome-cliente-2]-[dataAtual].txt

Ex: Joao-da-silva-01-11-2016.txt

I would like the information to be written to the generated file on the day only. If I arrived at midnight I would create another file, so that there is one file per day for each client.

  • is it possible to do this?

I searched for tutorials but found nothing like it.

Author: Marconi, 2016-11-01

2 answers

Raphael,

Follows as I did with NLOG, install the packages via nuget:

Install-Package NLog
Install-Package NLog.Config

No NLog.config include the following excerpt to targets:

  <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}-${environment:variable=CLIENT_NAME}.log"
        layout="${longdate} ${uppercase:${level}} ${message}" />

To log the error the way you want: client and current date in the file in 'fileName', just follow the pattern for what you need.

        NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        try
        {
            Environment.SetEnvironmentVariable("CLIENT_NAME", "Cliente 001");
            throw new Exception("Cliente 001 error");           
        }
        catch (Exception e)
        {
            logger.Error(e.Message);
        }

The date that the variable {shortdate} creates in this format "2016-11-03", if necessary, create another environment variable for its context.

 2
Author: Rodrigo, 2016-11-03 14:41:36

In the NLog file.Config I configure the file name like this

 fileName="/erros/${date:format=yyyy\MM}//${date:format=dd} - ${event-properties:item=name}.json">

And to log in do the following:

    Logger log = LogManager.GetCurrentClassLogger();
    LogEventInfo theEvent = new LogEventInfo(LogLevel.Fatal, "", e.Message);
    theEvent.Properties["name"] = "Nome";
    log.Log(theEvent);
 2
Author: Marco Vinicius Soares Dalalba, 2016-11-03 18:38:23