Purnima Naik
Purnima Naik

Reputation: 2683

How to log specific data and properties in nlog in .net core

I am using NLog for logging messages in .net core.

Following is the method which does the logging job for me. It is able to log properties too. And it writes to file, only when I call this method.

    private static void WriteLog(LogEvent logEvent)
    {
        var log = LogManager.GetLogger(logEvent.Logger);

        LogEventInfo logMsg = new LogEventInfo();
        logMsg.Message = logEvent.Message;
        logMsg.Level = logEvent.LogLevel;
        logMsg.Properties.Add("Title", logEvent.Title);
        logMsg.Properties.Add("Name", "abc");
        if (!string.IsNullOrEmpty(logEvent.StackTrace))
        {
            logMsg.Properties.Add("StackTrace", "Stack Trace: " + logEvent.StackTrace + Environment.NewLine);
        }
        if (!string.IsNullOrEmpty(logEvent.InnerException))
        {
            logMsg.Properties.Add("InnerException", "Inner Exception: " + logEvent.InnerException + Environment.NewLine);
        }
        log.Log(logMsg);
    }

It is not logging messages like:

"Executing ObjectResult, writing value Microsoft.AspNetCore.Mvc.ControllerContext."

"Request starting HTTP/1.1 GET http://localhost:5000/api/"

I want to achieve similar functionality by adding NLog to .net core. I added NLog in StartUp.cs as follows:

loggerFactory.AddNLog();

But by adding NLog in above mentioned way, it logs all the messages related to action execution. But I don't want these messages.

I want NLog to log messages by using LogInformation(). Plus how to pass properties like 'StackTrace' and 'InnerException' over here.

_logger.LogInformation("Home controller and Index action - logged");

Upvotes: 0

Views: 1631

Answers (1)

truemedia
truemedia

Reputation: 1062

To limit what is logged automatically, you may want to look at the logging level you have set in nlog.config and in Startup.cs. For example, this will only log messages automatically that are "Info" or higher (Warn, Error and Fatal) but not Trace or Debug. It will also only log messages for Classes in the namespace, "MyNamespace".

<rules>
    <!-- Level can be: Trace, Debug, Info, Warn, Error, Fatal  -->
    <logger name="MyNamespace.*" minlevel="Info" writeTo="DBLogger" final="true" />
</rules>

To save the Exception and stack trace, you should use the _logger.Log() method instead:

try { ... }
catch(Exception ex) {
   _logger.Log(LogLevel.Error, "Message", ex);
}

The stacktrace will be available to be logged with the exception.

Here is some additional information of how to parameterize the log messages you save.

Upvotes: 1

Related Questions