This post was most recently updated on July 29th, 2024
Nlog is an open source log platform through which we can log an activity of an application and store in file, database and even in azure blob storage.
Install following NuGet packages in your project:
1. Install-Package NLog-Version 4.7.10
2. Install-Package NLog.Web.AspNetCore- Version 4.12.0
3. Install-Package Microsoft.Data.SqlClient- Version 3.0.0
4. Install-Package Microsoft.Extensions.Logging.Console- Version 5.0.0
Create nlog.config file and add this:
Select Copy if newer against Copy to Output Directory in the Properties of the nlog.config file
Create a table in database where you want to store the logs
CREATE TABLE [dbo].[Logs](
[ID] [int] IDENTITY(1,1) NOT NULL,
[MachineName] [nvarchar](200) NULL,
[Logged] [datetime] NOT NULL,
[Level] [varchar](5) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[Logger] [nvarchar](300) NULL,
[Properties] [nvarchar](max) NULL,
[Callsite] [nvarchar](300) NULL,
[Exception] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.Logs] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Create a stored procedure to update the log entry in to the table
Create PROCEDURE [dbo].[usp_Logs_AddEntry] (
@machineName nvarchar(200),
@logged datetime,
@level varchar(5),
@message nvarchar(max),
@logger nvarchar(300),
@properties nvarchar(max),
@callsite nvarchar(300),
@exception nvarchar(max)
) AS
BEGIN
INSERT INTO [dbo].[Logs] (
[MachineName],
[Logged],
[Level],
[Message],
[Logger],
[Properties],
[Callsite],
[Exception]
) VALUES (
@machineName,
@logged,
@level,
@message,
@logger,
@properties,
@callsite,
@exception
);
END
Add the connection string in appsettings.json
“Logging”: {
“IncludeScopes”: false,
“LogLevel”: {
“Default”: “Trace”,
“Microsoft”: “Warning”,
“Microsoft.Hosting.Lifetime”: “Information”
},
“NLog”: “Data Source=[Name of the data source];Initial Catalog=*****;User ID=*****; Password=*****”
}
Add logging in Program.cs:
public class Program
{
public static void Main(string[] args)
{
var logger = NLogBuilder.ConfigureNLog(“nlog.config”).GetCurrentClassLogger();
try
{
logger.Debug(“Starting host builder”);
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
logger.Error(exception, “Stopped program because of exception”);
throw;
}
finally
{
NLog.LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog();
}
Inject ILogger to the controller. Inside your controller, let’s call it HomeController, inject the ILogger interface.
public HomeController(ILogger
{
_logger = logger;
}
Start Logging.
public IActionResult Index()
{
_logger.LogInformation(“The main page has been accessed”);
if (_appSettings.IsADFSLogin)
{
if (HttpContext.User != null)
{
SetUserDetails(“setUser”);
}
var objUserSession = HttpContext.Session.GetObjectFromJson
if (objUserSession == null)
{
return Challenge(“aad”);
}
else
{
return View();
}
}
else
{
return View();
}
}