Log Generation with NLog?

0

I am using NLog , and for each client logged into the system I would like to create a behavior for generating logs 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 only on the day. If he arrived at midnight he would another file, so that there is one file per day for each client.

  • Is it possible to do this?

I searched for tutorials but did not find anything like it.

    
asked by anonymous 01.11.2016 / 14:32

2 answers

1

Raphael,

Here's how I did with NLOG, install packages via nuget:

Install-Package NLog
Install-Package NLog.Config

In NLog.config include the following strings to the 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 the variable creates in this format "2016-11-03", if necessary, create another environment variable for its context.

    
03.11.2016 / 15:41
1

In the NLog.Config file I set the file name this way

 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);
    
03.11.2016 / 19:38