Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/damienbod/aspnetcorenlog
ASP.NET Core NLog MS SQL Server PostgreSQL MySQL Elasticsearch
https://github.com/damienbod/aspnetcorenlog
asp-net-core aspnet-core elasticsearch logging mysql nlog postgresql sql sql-server
Last synced: 2 months ago
JSON representation
ASP.NET Core NLog MS SQL Server PostgreSQL MySQL Elasticsearch
- Host: GitHub
- URL: https://github.com/damienbod/aspnetcorenlog
- Owner: damienbod
- License: mit
- Created: 2016-08-17T04:22:09.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2024-01-16T19:59:32.000Z (about 1 year ago)
- Last Synced: 2024-11-01T13:42:10.130Z (3 months ago)
- Topics: asp-net-core, aspnet-core, elasticsearch, logging, mysql, nlog, postgresql, sql, sql-server
- Language: C#
- Homepage: https://damienbod.com/2016/08/17/asp-net-core-logging-with-nlog-and-microsoft-sql-server/
- Size: 130 KB
- Stars: 60
- Watchers: 6
- Forks: 27
- Open Issues: 6
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# NLog posts in this series:
- ASP.NET Core logging with NLog and Microsoft SQL Server
- ASP.NET Core logging with NLog and Elasticsearch
- Settings the NLog database connection string in the ASP.NET Core appsettings.json
- .NET Core logging to MySQL using NLog
- .NET Core logging with NLog and PostgreSQL
# History
2020-01-12 Updated to .NET Core 3.1, NLog.Web.AspNetCore 4.9.0
2018-04-04 Updated to .NET Core 2.0, NLog 4.5.1, and Elasticsearch Nuget package
## ASP.NET Core logging with NLog and MS SQLServer
This article shows how to setup logging in an ASP.NET Core application which logs to a Microsoft SQL Server using NLog.
The NLog.Web.AspNetCore Nuget package is added to the dependencies in the csproj file.
```xml
netcoreapp3.1
PreserveNewest
```
Now a nlog.config file is created and added to the project. This file contains the configuration for NLog. In the file, the targets for the logs are defined as well as the rules. An internal log file is also defined, so that if something is wrong with the logging configuration, you can find out why. The ${gdc:item=configDir} is set in the application code.
```xml
${gdc:item=connectionString}
insert into dbo.Log (
Application, Logged, Level, Message,
Logger, CallSite, Exception
) values (
@Application, @Logged, @Level, @Message,
@Logger, @Callsite, @Exception
);
```
Now the database can be setup. You can create a new database, or use and existing one and add the dbo.Log table to it using the script below.
```sql
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[Log] (
[Id] [int] IDENTITY(1,1) NOT NULL,
[Application] [nvarchar](50) NOT NULL,
[Logged] [datetime] NOT NULL,
[Level] [nvarchar](50) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[Logger] [nvarchar](250) NULL,
[Callsite] [nvarchar](max) NULL,
[Exception] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.Log] 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]```
The table in the database must match the configuration defined in the nlog.config file. The database target defines the connection string, the command used to add a log and also the parameters required.
You can change this as required. As yet, most of the NLog parameters, do not work with ASP.NET Core, but this will certainly change as it is in early development. The NLog.Web Nuget package, when completed will contain the ASP.NET Core parameters.
Now NLog can be added to the application in the Startup class in the configure method. The AddNLog extension method is used and the logging directory can be defined.
```csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
GlobalDiagnosticsContext.Set("configDir", "C:\\git\\damienbod\\AspNetCoreNlog\\Logs");
GlobalDiagnosticsContext.Set("connectionString", Configuration.GetConnectionString("DefaultConnection"));if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}app.UseDefaultFiles();
app.UseStaticFiles();app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}```
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Web;namespace AspNetCoreNlog
{
public static class Program
{
public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
//NLog: catch setup errors
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog(); // NLog: Setup NLog for Dependency injection
}
}```
Now the logging can be used, using the default logging framework from ASP.NET Core.
An example of an ActionFilter
```csharp
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;namespace AspNetCoreNlog
{
public class LogFilter : ActionFilterAttribute
{
private readonly ILogger _logger;public LogFilter(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger("LogFilter");
}public override void OnActionExecuting(ActionExecutingContext context)
{
_logger.LogInformation("OnActionExecuting");
base.OnActionExecuting(context);
}public override void OnActionExecuted(ActionExecutedContext context)
{
_logger.LogInformation("OnActionExecuted");
base.OnActionExecuted(context);
}public override void OnResultExecuting(ResultExecutingContext context)
{
_logger.LogInformation("OnResultExecuting");
base.OnResultExecuting(context);
}public override void OnResultExecuted(ResultExecutedContext context)
{
_logger.LogInformation("OnResultExecuted");
base.OnResultExecuted(context);
}
}
}```
The action filter is added in the Startup ConfigureServices services.
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton();
// Add framework services.
services.AddControllers();services.AddScoped();
}```
And some logging can be added to a MVC controller.
```csharp
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;namespace AspNetCoreNlog.Controllers
{
[ServiceFilter(typeof(LogFilter))]
[Route("api/[controller]")]
public class ValuesController : Controller
{
private ILogger _logger;public ValuesController(ILogger logger)
{
_logger = logger;
}[HttpGet]
public IEnumerable Get()
{
_logger.LogCritical("nlog is working from a controller");
throw new ArgumentException("way wrong");
return new string[] { "value1", "value2" };
}```
When the application is started, the logs are written to a local file in the Logs folder and also to the database.
## Links
https://github.com/NLog/NLog.Web
https://github.com/NLog/NLog.Extensions.Logging
https://github.com/NLog
https://docs.asp.net/en/latest/fundamentals/logging.html
https://msdn.microsoft.com/en-us/magazine/mt694089.aspx
https://github.com/nlog/NLog/wiki/Database-target