How to Use Nlog with .Net Core 2.0 Application
1. Introduction
Logging is heart of the application. logging is very important for debugging and troubleshooting as well as for smoothness of application.
with the help of logging we can have end-to-end visibility for on-premise systems, to only give a fraction of that visibility for cloud-based systems. It can be difficult to instrument the cloud and, thus, alternative approaches, like logging, are required to give visibility into cloud-based components which otherwise can become black boxes from a performance or system monitoring perspective.
2. Install Nuget Package For nlog
To use Nlog logging you need to first add Nlog pluging for adding pluging you can do it by different way.
1) Manage Nuget Packages.
2) Nuget command.
you can find nuget command for Nlog on mentioned link : Click Here
3. Create and add Nlog config file
we need to create Nlog.config file at root of project were we can keep nlog related configration.
Example :
commandText="INSERT INTO TableName (LOG_LEVEL,LOGGER_NAME,SESSION_ID,BROWSER_DETAIL) values(:LOGLEVEL,:LOGGERNAME,:SESSIONID,:BROWSERDETAIL)">
For more detail Please click on mentioned link : Click Here
we need to load nlog related configration in relvent startup file. please refer below code.
NLog.GlobalDiagnosticsContext.Set("defaultConnection", Connection string);
NLog.LogManager.LoadConfiguration(env.ContentRootPath + "\\NLog.config");
5. Custom Nlog Manager.
Manager Class :
public static class NLogManager {
public static ILogger _logger = NLog.LogManager.GetCurrentClassLogger();
public static void InfoLog(NLogData nLogData) {
LogEventInfo theEvent = new LogEventInfo(LogLevel.Info, NLogManager._logger.Name, nLogData.Message);
SetLogEventInfo(theEvent, nLogData);
_logger.Log(theEvent);
}
public static void DebugLog(NLogData nLogData) {
LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, NLogManager._logger.Name, nLogData.Message);
SetLogEventInfo(theEvent, nLogData);
_logger.Log(theEvent);
}
public static void ErrorLog(NLogData nLogData) {
LogEventInfo theEvent = new LogEventInfo(LogLevel.Error, NLogManager._logger.Name, nLogData.Message);
SetLogEventInfo(theEvent, nLogData);
_logger.Log(theEvent);
}
}
Custom Event parameter for logging :
private static void SetLogEventInfo(LogEventInfo theEvent, NLogData nLogData) {
theEvent.Properties["SessionId"] = nLogData.SessionId;
theEvent.Properties["BrowserDetail"] = nLogData.BrowserDetail;
}
if you need to log more parameter into database just add property in above method and same add into Nlog.config file.
Model for NLog logging.
public class NLogData {
public string SessionId {
get;
set;
}
public string BrowserDetail {
get;
set;
}
}
Happy Coding. Please Add comment if you have any query.
Leave a Comment