Generation of Logs with Nlog?

Asked

Viewed 2,406 times

1

I’m using the Nlog, and for each client logged into the system I would like to create a log generation behavior 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 in the generated file only on the day. If I arrived at midnight I would create another file, so that there is one file per day for each client.

  • It is possible to do this?

I searched for tutorials but found nothing like.

  • 1

    On the question of 'per day' of a look on this wiki page nlog, in the 'Time-based archival file' section. Unfortunately it is in English.

2 answers

2


Raphael,

Follow as I did with the NLOG, install the Packages via nuget:

Install-Package NLog
Install-Package NLog.Config

In Nlog.config include to targets the section below:

  <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 default 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 your context.

  • Thank you very much, Rodrigo! I did it this way but it did not generate the folder with the file, you have idea of what can be?

  • 1

    Raphael, according to the filename, will be created a folder called logs within the application executable location, (in our scenario will be created within the Bin folder) with the file named 2016-11-03-Client 001.txt. Sure that no log file has been generated?

  • Yes, no file :( Strange because I made the settings without any problem. I’ll give a check.

  • 1

    Raphael, follow the repository to test: https://github.com/rodrigoacr/NLogExample

  • Ah, I thought! The "writeTo" was not pointing to the target name. Thank you very much Rodrigo! Thanks!

2

In the file Nlog.Config 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 as follows:

    Logger log = LogManager.GetCurrentClassLogger();
    LogEventInfo theEvent = new LogEventInfo(LogLevel.Fatal, "", e.Message);
    theEvent.Properties["name"] = "Nome";
    log.Log(theEvent);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.