{"id":15410676,"url":"https://github.com/damienbod/aspnetcorenlog","last_synced_at":"2026-03-01T15:01:59.518Z","repository":{"id":66359407,"uuid":"65875653","full_name":"damienbod/AspNetCoreNlog","owner":"damienbod","description":"ASP.NET Core NLog MS SQL Server PostgreSQL MySQL Elasticsearch","archived":false,"fork":false,"pushed_at":"2024-01-16T19:59:32.000Z","size":133,"stargazers_count":59,"open_issues_count":6,"forks_count":27,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-19T04:33:43.884Z","etag":null,"topics":["asp-net-core","aspnet-core","elasticsearch","logging","mysql","nlog","postgresql","sql","sql-server"],"latest_commit_sha":null,"homepage":"https://damienbod.com/2016/08/17/asp-net-core-logging-with-nlog-and-microsoft-sql-server/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/damienbod.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-08-17T04:22:09.000Z","updated_at":"2025-02-12T06:37:25.000Z","dependencies_parsed_at":"2024-10-19T16:28:48.507Z","dependency_job_id":null,"html_url":"https://github.com/damienbod/AspNetCoreNlog","commit_stats":{"total_commits":73,"total_committers":2,"mean_commits":36.5,"dds":0.0273972602739726,"last_synced_commit":"66d570e6e3600844f54cbac9d92c8599b9d41513"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/damienbod/AspNetCoreNlog","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2FAspNetCoreNlog","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2FAspNetCoreNlog/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2FAspNetCoreNlog/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2FAspNetCoreNlog/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/damienbod","download_url":"https://codeload.github.com/damienbod/AspNetCoreNlog/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2FAspNetCoreNlog/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29973112,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-01T14:44:57.896Z","status":"ssl_error","status_checked_at":"2026-03-01T14:43:27.662Z","response_time":124,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asp-net-core","aspnet-core","elasticsearch","logging","mysql","nlog","postgresql","sql","sql-server"],"created_at":"2024-10-01T16:45:47.496Z","updated_at":"2026-03-01T15:01:59.492Z","avatar_url":"https://github.com/damienbod.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"\r\n# NLog posts in this series:\r\n\r\n\u003col\u003e\r\n\t\u003cli\u003e\u003ca href=\"https://damienbod.com/2016/08/17/asp-net-core-logging-with-nlog-and-microsoft-sql-server/\"\u003eASP.NET Core logging with NLog and Microsoft SQL Server\u003c/a\u003e\u003c/li\u003e\r\n\t\u003cli\u003e\u003ca href=\"https://damienbod.com/2016/08/20/asp-net-core-logging-with-nlog-and-elasticsearch/\"\u003eASP.NET Core logging with NLog and Elasticsearch\u003c/a\u003e\u003c/li\u003e\r\n\t\u003cli\u003e\u003ca href=\"https://damienbod.com/2016/09/22/setting-the-nlog-database-connection-string-in-the-asp-net-core-appsettings-json/\"\u003eSettings the NLog database connection string in the ASP.NET Core appsettings.json\u003c/a\u003e\u003c/li\u003e\r\n\t\u003cli\u003e\u003ca href=\"https://damienbod.com/2017/03/03/net-core-logging-to-mysql-using-nlog/\"\u003e.NET Core logging to MySQL using NLog\u003c/a\u003e\u003c/li\u003e\r\n\t\u003cli\u003e\u003ca href=\"https://damienbod.com/2017/03/29/net-core-asp-net-core-logging-with-nlog-and-postgresql/\"\u003e.NET Core logging with NLog and PostgreSQL\u003c/a\u003e\u003c/li\u003e\r\n\t\r\n\u003c/ol\u003e\r\n\r\n# History\r\n\r\n2020-01-12 Updated to .NET Core 3.1, NLog.Web.AspNetCore 4.9.0\r\n\r\n2018-04-04 Updated to .NET Core 2.0, NLog 4.5.1, and Elasticsearch Nuget package\r\n\r\n\r\n## ASP.NET Core logging with NLog and MS SQLServer\r\n\r\nThis article shows how to setup logging in an ASP.NET Core application which logs to a Microsoft SQL Server using NLog.\r\n\r\nThe NLog.Web.AspNetCore Nuget package is added to the dependencies in the csproj file.\r\n\r\n```xml\r\n\u003cProject Sdk=\"Microsoft.NET.Sdk.Web\"\u003e\r\n  \r\n  \u003cPropertyGroup\u003e\r\n    \u003cTargetFramework\u003enetcoreapp3.1\u003c/TargetFramework\u003e\r\n  \u003c/PropertyGroup\u003e\r\n\r\n  \u003cItemGroup\u003e\r\n    \u003cPackageReference Include=\"NLog.Targets.ElasticSearch\" Version=\"7.1.1\" /\u003e\r\n    \u003cPackageReference Include=\"NLog.Web.AspNetCore\" Version=\"4.9.0\" /\u003e\r\n    \u003cPackageReference Include=\"Microsoft.EntityFrameworkCore.Tools\" Version=\"3.1.0\" PrivateAssets=\"All\" /\u003e\r\n    \u003cPackageReference Include=\"Swashbuckle.AspNetCore\" Version=\"5.0.0-rc5\" /\u003e\r\n    \u003cPackageReference Include=\"System.Data.SqlClient\" Version=\"4.8.0\" /\u003e\r\n  \u003c/ItemGroup\u003e\r\n  \r\n  \u003cItemGroup\u003e\r\n    \u003cDotNetCliToolReference Include=\"Microsoft.VisualStudio.Web.CodeGeneration.Tools\" Version=\"2.0.0\" /\u003e\r\n  \u003c/ItemGroup\u003e\r\n  \r\n  \u003cItemGroup\u003e\r\n    \u003cContent Update=\"nlog.config\"\u003e\r\n      \u003cCopyToOutputDirectory\u003ePreserveNewest\u003c/CopyToOutputDirectory\u003e\r\n    \u003c/Content\u003e\r\n  \u003c/ItemGroup\u003e\r\n\u003c/Project\u003e\r\n```\r\n\r\n\r\nNow 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.\r\n\r\n```xml\r\n\u003c?xml version=\"1.0\" encoding=\"utf-8\" ?\u003e\r\n\u003cnlog xmlns=\"http://www.nlog-project.org/schemas/NLog.xsd\"\r\n      xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n      autoReload=\"true\"\r\n      internalLogLevel=\"Warn\"\r\n      internalLogFile=\"C:\\git\\damienbod\\AspNetCoreNlog\\Logs\\internal-nlog.txt\"\u003e\r\n    \r\n            \r\n  \u003ctargets\u003e\r\n    \u003ctarget xsi:type=\"File\" name=\"allfile\" fileName=\"${gdc:item=configDir}\\nlog-all.log\"\r\n                layout=\"${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}\" /\u003e\r\n\r\n    \u003ctarget xsi:type=\"File\" name=\"ownFile-web\" fileName=\"${gdc:item=configDir}\\nlog-own.log\"\r\n             layout=\"${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|  ${message} ${exception}\" /\u003e\r\n\r\n    \u003ctarget xsi:type=\"Null\" name=\"blackhole\" /\u003e\r\n        \r\n    \u003ctarget name=\"database\" xsi:type=\"Database\" \u003e\r\n\r\n      \u003cconnectionString\u003e${gdc:item=connectionString}\u003c/connectionString\u003e\r\n\u003c!--\r\n  Remarks:\r\n    The appsetting layouts require the NLog.Extended assembly.\r\n    The aspnet-* layouts require the NLog.Web assembly.\r\n    The Application value is determined by an AppName appSetting in Web.config.\r\n    The \"NLogDb\" connection string determines the database that NLog write to.\r\n    The create dbo.Log script in the comment below must be manually executed.\r\n\r\n  Script for creating the dbo.Log table.\r\n\r\n  SET ANSI_NULLS ON\r\n  SET QUOTED_IDENTIFIER ON\r\n  CREATE TABLE [dbo].[Log] (\r\n      [Id] [int] IDENTITY(1,1) NOT NULL,\r\n      [Application] [nvarchar](50) NOT NULL,\r\n      [Logged] [datetime] NOT NULL,\r\n      [Level] [nvarchar](50) NOT NULL,\r\n      [Message] [nvarchar](max) NOT NULL,\r\n      [Logger] [nvarchar](250) NULL,\r\n      [Callsite] [nvarchar](max) NULL,\r\n      [Exception] [nvarchar](max) NULL,\r\n    CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([Id] ASC)\r\n      WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]\r\n  ) ON [PRIMARY]\r\n--\u003e\r\n\r\n          \u003ccommandText\u003e\r\n              insert into dbo.Log (\r\n              Application, Logged, Level, Message,\r\n              Logger, CallSite, Exception\r\n              ) values (\r\n              @Application, @Logged, @Level, @Message,\r\n              @Logger, @Callsite, @Exception\r\n              );\r\n          \u003c/commandText\u003e\r\n\r\n          \u003cparameter name=\"@application\" layout=\"AspNetCoreNlog\" /\u003e\r\n          \u003cparameter name=\"@logged\" layout=\"${date}\" /\u003e\r\n          \u003cparameter name=\"@level\" layout=\"${level}\" /\u003e\r\n          \u003cparameter name=\"@message\" layout=\"${message}\" /\u003e\r\n\r\n          \u003cparameter name=\"@logger\" layout=\"${logger}\" /\u003e\r\n          \u003cparameter name=\"@callSite\" layout=\"${callsite:filename=true}\" /\u003e\r\n          \u003cparameter name=\"@exception\" layout=\"${exception:tostring}\" /\u003e\r\n      \u003c/target\u003e\r\n      \r\n  \u003c/targets\u003e\r\n\r\n  \u003crules\u003e\r\n    \u003c!--All logs, including from Microsoft--\u003e\r\n    \u003clogger name=\"*\" minlevel=\"Trace\" writeTo=\"allfile\" /\u003e\r\n      \r\n    \u003clogger name=\"*\" minlevel=\"Trace\" writeTo=\"database\" /\u003e\r\n      \r\n    \u003c!--Skip Microsoft logs and so log only own logs--\u003e\r\n    \u003clogger name=\"Microsoft.*\" minlevel=\"Trace\" writeTo=\"blackhole\" final=\"true\" /\u003e\r\n    \u003clogger name=\"*\" minlevel=\"Trace\" writeTo=\"ownFile-web\" /\u003e\r\n  \u003c/rules\u003e\r\n\u003c/nlog\u003e\r\n```\r\n\r\n\r\nNow 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. \r\n\r\n```sql\r\n  SET ANSI_NULLS ON\r\n  SET QUOTED_IDENTIFIER ON\r\n  CREATE TABLE [dbo].[Log] (\r\n      [Id] [int] IDENTITY(1,1) NOT NULL,\r\n      [Application] [nvarchar](50) NOT NULL,\r\n      [Logged] [datetime] NOT NULL,\r\n      [Level] [nvarchar](50) NOT NULL,\r\n      [Message] [nvarchar](max) NOT NULL,\r\n      [Logger] [nvarchar](250) NULL,\r\n      [Callsite] [nvarchar](max) NULL,\r\n      [Exception] [nvarchar](max) NULL,\r\n    CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([Id] ASC)\r\n      WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]\r\n  ) ON [PRIMARY]\r\n\r\n```\r\n\r\nThe 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.\r\n\r\nYou 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.\r\n\r\n\r\nNow 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.\r\n\r\n```csharp\r\npublic void Configure(IApplicationBuilder app, IWebHostEnvironment env)\r\n{\r\n    GlobalDiagnosticsContext.Set(\"configDir\", \"C:\\\\git\\\\damienbod\\\\AspNetCoreNlog\\\\Logs\");\r\n    GlobalDiagnosticsContext.Set(\"connectionString\", Configuration.GetConnectionString(\"DefaultConnection\"));\r\n\r\n    if (env.IsDevelopment())\r\n    {\r\n        app.UseDeveloperExceptionPage();\r\n    }\r\n    else\r\n    {\r\n        app.UseExceptionHandler(\"/Home/Error\");\r\n    }\r\n\r\n\r\n    app.UseDefaultFiles();\r\n    app.UseStaticFiles();\r\n\r\n    app.UseRouting();\r\n\r\n    app.UseEndpoints(endpoints =\u003e\r\n    {\r\n        endpoints.MapControllerRoute(\r\n            name: \"default\",\r\n            pattern: \"{controller=Home}/{action=Index}/{id?}\");\r\n    });\r\n}\r\n\r\n```\r\n\r\n```csharp\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.AspNetCore.Hosting;\r\nusing Microsoft.Extensions.Configuration;\r\nusing Microsoft.Extensions.Hosting;\r\nusing Microsoft.Extensions.Logging;\r\nusing NLog;\r\nusing NLog.Web;\r\n\r\nnamespace AspNetCoreNlog\r\n{\r\n    public static class Program\r\n    {\r\n        public static void Main(string[] args)\r\n        {\r\n            var logger = NLog.Web.NLogBuilder.ConfigureNLog(\"nlog.config\").GetCurrentClassLogger();\r\n            try\r\n            {\r\n                logger.Debug(\"init main\");\r\n                CreateHostBuilder(args).Build().Run();\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                //NLog: catch setup errors\r\n                logger.Error(exception, \"Stopped program because of exception\");\r\n                throw;\r\n            }\r\n            finally\r\n            {\r\n                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)\r\n                NLog.LogManager.Shutdown();\r\n            }\r\n        }\r\n\r\n        public static IHostBuilder CreateHostBuilder(string[] args) =\u003e\r\n          Host.CreateDefaultBuilder(args)\r\n            .ConfigureWebHostDefaults(webBuilder =\u003e\r\n            {\r\n                webBuilder.UseStartup\u003cStartup\u003e();\r\n            })\r\n            .ConfigureLogging(logging =\u003e\r\n            {\r\n                logging.ClearProviders();\r\n                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);\r\n            })\r\n            .UseNLog();  // NLog: Setup NLog for Dependency injection\r\n    }\r\n}\r\n\r\n```\r\n\r\nNow the logging can be used, using the default logging framework from ASP.NET Core.\r\n\r\nAn example of an ActionFilter\r\n\r\n```csharp\r\nusing Microsoft.AspNetCore.Mvc.Filters;\r\nusing Microsoft.Extensions.Logging;\r\n\r\nnamespace AspNetCoreNlog\r\n{\r\n    public class LogFilter : ActionFilterAttribute\r\n    {\r\n        private readonly ILogger _logger;\r\n\r\n        public LogFilter(ILoggerFactory loggerFactory)\r\n        {\r\n            _logger = loggerFactory.CreateLogger(\"LogFilter\");\r\n        }\r\n\r\n        public override void OnActionExecuting(ActionExecutingContext context)\r\n        {\r\n            _logger.LogInformation(\"OnActionExecuting\");\r\n            base.OnActionExecuting(context);\r\n        }\r\n\r\n        public override void OnActionExecuted(ActionExecutedContext context)\r\n        {\r\n            _logger.LogInformation(\"OnActionExecuted\");\r\n            base.OnActionExecuted(context);\r\n        }\r\n\r\n        public override void OnResultExecuting(ResultExecutingContext context)\r\n        {\r\n            _logger.LogInformation(\"OnResultExecuting\");\r\n            base.OnResultExecuting(context);\r\n        }\r\n\r\n        public override void OnResultExecuted(ResultExecutedContext context)\r\n        {\r\n            _logger.LogInformation(\"OnResultExecuted\");\r\n            base.OnResultExecuted(context);\r\n        }\r\n    }\r\n}\r\n\r\n\r\n```\r\n\r\nThe action filter is added in the Startup ConfigureServices services.\r\n\r\n```csharp\r\n public void ConfigureServices(IServiceCollection services)\r\n{\r\n\tservices.AddSingleton\u003cIHttpContextAccessor, HttpContextAccessor\u003e();\r\n\t// Add framework services.\r\n\tservices.AddControllers();\r\n\r\n\tservices.AddScoped\u003cLogFilter\u003e();\r\n}\r\n\r\n```\r\n\r\n And some logging can be added to a MVC controller.\r\n\r\n```csharp\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing Microsoft.AspNetCore.Mvc;\r\nusing Microsoft.Extensions.Logging;\r\n\r\nnamespace AspNetCoreNlog.Controllers\r\n{\r\n    [ServiceFilter(typeof(LogFilter))]\r\n    [Route(\"api/[controller]\")]\r\n    public class ValuesController : Controller\r\n    {\r\n        private  ILogger\u003cValuesController\u003e _logger;\r\n\r\n        public ValuesController(ILogger\u003cValuesController\u003e logger)\r\n        {\r\n            _logger = logger;\r\n        }\r\n\r\n        [HttpGet]\r\n        public IEnumerable\u003cstring\u003e Get()\r\n        {\r\n            _logger.LogCritical(\"nlog is working from a controller\");\r\n            throw new ArgumentException(\"way wrong\");\r\n            return new string[] { \"value1\", \"value2\" };\r\n        }\r\n\r\n```\r\n\r\nWhen the application is started, the logs are written to a local file in the Logs folder and also to the database. \r\n\r\n    \r\n\u003cimg src=\"https://damienbod.files.wordpress.com/2016/08/sqlaspnetdatabselogger_01.png?w=600\" alt=\"sqlaspnetdatabselogger_01\" width=\"600\" height=\"287\" class=\"alignnone size-medium wp-image-7058\" /\u003e\r\n\r\n## Links\r\n\r\nhttps://github.com/NLog/NLog.Web\r\n\r\nhttps://github.com/NLog/NLog.Extensions.Logging\r\n\r\nhttps://github.com/NLog\r\n\r\nhttps://docs.asp.net/en/latest/fundamentals/logging.html\r\n\r\nhttps://msdn.microsoft.com/en-us/magazine/mt694089.aspx\r\n\r\nhttps://github.com/nlog/NLog/wiki/Database-target\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdamienbod%2Faspnetcorenlog","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdamienbod%2Faspnetcorenlog","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdamienbod%2Faspnetcorenlog/lists"}