├── .gitignore ├── AspNetCoreNlog.sln ├── LICENSE ├── README.md ├── sqlaspnetdatabselogger_01.png └── src ├── AspNetCoreNlog ├── AspNetCoreNlog.csproj ├── Controllers │ └── ValuesController.cs ├── LogFilter.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── appsettings.json ├── nlog.config ├── nlog.database.config ├── nlog.elasticsearch.config ├── nlog.file.config └── web.config ├── ConsoleNLog ├── ConsoleNLog.csproj ├── Program.cs ├── appsettings.json └── nlog.config ├── ConsoleNLogMySQL ├── ConsoleNLogMySQL.csproj ├── Program.cs └── nlog.config └── ConsoleNLogPostgreSQL ├── ConsoleNLogPostgreSQL.csproj ├── Program.cs └── nlog.config /.gitignore: -------------------------------------------------------------------------------- 1 | Logs 2 | .vs/AspNetCoreNlog/v14/.suo 3 | src/AspNetCoreNlog/AspNetCoreNlog.xproj.user 4 | src/AspNetCoreNlog/bin 5 | src/AspNetCoreNlog/obj 6 | src/AspNetCoreNlog/project.lock.json 7 | .vs 8 | src/NLog.Targets.ElasticSearch/obj 9 | src/NLog.Targets.ElasticSearch/bin 10 | src/NLog.Targets.ElasticSearch/project.lock.json 11 | src/NLog.Targets.ElasticSearch/NLog.Targets.ElasticSearch.xproj.user 12 | src/AspNetCoreNlog/nlog-all.log 13 | src/ConsoleNLog/bin 14 | src/ConsoleNLog/obj 15 | src/ConsoleNLog/project.lock.json 16 | src/ConsoleNLog/ConsoleNLog.xproj.user 17 | src/ConsoleNLogMySQL/bin 18 | src/ConsoleNLogMySQL/obj 19 | src/ConsoleNLogPostgreSQL/bin 20 | src/ConsoleNLogPostgreSQL/obj 21 | -------------------------------------------------------------------------------- /AspNetCoreNlog.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29609.76 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{D82C9880-2134-41A3-B428-24AC5318F17E}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{50E0080F-878A-4A06-A4E0-6840F751EF9F}" 9 | ProjectSection(SolutionItems) = preProject 10 | README.md = README.md 11 | EndProjectSection 12 | EndProject 13 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNetCoreNlog", "src\AspNetCoreNlog\AspNetCoreNlog.csproj", "{697DEC29-7B76-4B02-9533-FC131647034E}" 14 | EndProject 15 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleNLog", "src\ConsoleNLog\ConsoleNLog.csproj", "{1012D69F-4831-4009-9600-7D347334B9DD}" 16 | EndProject 17 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleNLogMySQL", "src\ConsoleNLogMySQL\ConsoleNLogMySQL.csproj", "{E0455B9C-9EEF-421E-9658-4182574195CC}" 18 | EndProject 19 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleNLogPostgreSQL", "src\ConsoleNLogPostgreSQL\ConsoleNLogPostgreSQL.csproj", "{51704BC7-BF0C-4403-950D-61BE77156F1C}" 20 | EndProject 21 | Global 22 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 23 | Debug|Any CPU = Debug|Any CPU 24 | Debug|x64 = Debug|x64 25 | Debug|x86 = Debug|x86 26 | Release|Any CPU = Release|Any CPU 27 | Release|x64 = Release|x64 28 | Release|x86 = Release|x86 29 | EndGlobalSection 30 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 31 | {697DEC29-7B76-4B02-9533-FC131647034E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {697DEC29-7B76-4B02-9533-FC131647034E}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {697DEC29-7B76-4B02-9533-FC131647034E}.Debug|x64.ActiveCfg = Debug|Any CPU 34 | {697DEC29-7B76-4B02-9533-FC131647034E}.Debug|x64.Build.0 = Debug|Any CPU 35 | {697DEC29-7B76-4B02-9533-FC131647034E}.Debug|x86.ActiveCfg = Debug|Any CPU 36 | {697DEC29-7B76-4B02-9533-FC131647034E}.Debug|x86.Build.0 = Debug|Any CPU 37 | {697DEC29-7B76-4B02-9533-FC131647034E}.Release|Any CPU.ActiveCfg = Release|Any CPU 38 | {697DEC29-7B76-4B02-9533-FC131647034E}.Release|Any CPU.Build.0 = Release|Any CPU 39 | {697DEC29-7B76-4B02-9533-FC131647034E}.Release|x64.ActiveCfg = Release|Any CPU 40 | {697DEC29-7B76-4B02-9533-FC131647034E}.Release|x64.Build.0 = Release|Any CPU 41 | {697DEC29-7B76-4B02-9533-FC131647034E}.Release|x86.ActiveCfg = Release|Any CPU 42 | {697DEC29-7B76-4B02-9533-FC131647034E}.Release|x86.Build.0 = Release|Any CPU 43 | {1012D69F-4831-4009-9600-7D347334B9DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 44 | {1012D69F-4831-4009-9600-7D347334B9DD}.Debug|Any CPU.Build.0 = Debug|Any CPU 45 | {1012D69F-4831-4009-9600-7D347334B9DD}.Debug|x64.ActiveCfg = Debug|Any CPU 46 | {1012D69F-4831-4009-9600-7D347334B9DD}.Debug|x64.Build.0 = Debug|Any CPU 47 | {1012D69F-4831-4009-9600-7D347334B9DD}.Debug|x86.ActiveCfg = Debug|Any CPU 48 | {1012D69F-4831-4009-9600-7D347334B9DD}.Debug|x86.Build.0 = Debug|Any CPU 49 | {1012D69F-4831-4009-9600-7D347334B9DD}.Release|Any CPU.ActiveCfg = Release|Any CPU 50 | {1012D69F-4831-4009-9600-7D347334B9DD}.Release|Any CPU.Build.0 = Release|Any CPU 51 | {1012D69F-4831-4009-9600-7D347334B9DD}.Release|x64.ActiveCfg = Release|Any CPU 52 | {1012D69F-4831-4009-9600-7D347334B9DD}.Release|x64.Build.0 = Release|Any CPU 53 | {1012D69F-4831-4009-9600-7D347334B9DD}.Release|x86.ActiveCfg = Release|Any CPU 54 | {1012D69F-4831-4009-9600-7D347334B9DD}.Release|x86.Build.0 = Release|Any CPU 55 | {E0455B9C-9EEF-421E-9658-4182574195CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 56 | {E0455B9C-9EEF-421E-9658-4182574195CC}.Debug|Any CPU.Build.0 = Debug|Any CPU 57 | {E0455B9C-9EEF-421E-9658-4182574195CC}.Debug|x64.ActiveCfg = Debug|Any CPU 58 | {E0455B9C-9EEF-421E-9658-4182574195CC}.Debug|x64.Build.0 = Debug|Any CPU 59 | {E0455B9C-9EEF-421E-9658-4182574195CC}.Debug|x86.ActiveCfg = Debug|Any CPU 60 | {E0455B9C-9EEF-421E-9658-4182574195CC}.Debug|x86.Build.0 = Debug|Any CPU 61 | {E0455B9C-9EEF-421E-9658-4182574195CC}.Release|Any CPU.ActiveCfg = Release|Any CPU 62 | {E0455B9C-9EEF-421E-9658-4182574195CC}.Release|Any CPU.Build.0 = Release|Any CPU 63 | {E0455B9C-9EEF-421E-9658-4182574195CC}.Release|x64.ActiveCfg = Release|Any CPU 64 | {E0455B9C-9EEF-421E-9658-4182574195CC}.Release|x64.Build.0 = Release|Any CPU 65 | {E0455B9C-9EEF-421E-9658-4182574195CC}.Release|x86.ActiveCfg = Release|Any CPU 66 | {E0455B9C-9EEF-421E-9658-4182574195CC}.Release|x86.Build.0 = Release|Any CPU 67 | {51704BC7-BF0C-4403-950D-61BE77156F1C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 68 | {51704BC7-BF0C-4403-950D-61BE77156F1C}.Debug|Any CPU.Build.0 = Debug|Any CPU 69 | {51704BC7-BF0C-4403-950D-61BE77156F1C}.Debug|x64.ActiveCfg = Debug|Any CPU 70 | {51704BC7-BF0C-4403-950D-61BE77156F1C}.Debug|x64.Build.0 = Debug|Any CPU 71 | {51704BC7-BF0C-4403-950D-61BE77156F1C}.Debug|x86.ActiveCfg = Debug|Any CPU 72 | {51704BC7-BF0C-4403-950D-61BE77156F1C}.Debug|x86.Build.0 = Debug|Any CPU 73 | {51704BC7-BF0C-4403-950D-61BE77156F1C}.Release|Any CPU.ActiveCfg = Release|Any CPU 74 | {51704BC7-BF0C-4403-950D-61BE77156F1C}.Release|Any CPU.Build.0 = Release|Any CPU 75 | {51704BC7-BF0C-4403-950D-61BE77156F1C}.Release|x64.ActiveCfg = Release|Any CPU 76 | {51704BC7-BF0C-4403-950D-61BE77156F1C}.Release|x64.Build.0 = Release|Any CPU 77 | {51704BC7-BF0C-4403-950D-61BE77156F1C}.Release|x86.ActiveCfg = Release|Any CPU 78 | {51704BC7-BF0C-4403-950D-61BE77156F1C}.Release|x86.Build.0 = Release|Any CPU 79 | EndGlobalSection 80 | GlobalSection(SolutionProperties) = preSolution 81 | HideSolutionNode = FALSE 82 | EndGlobalSection 83 | GlobalSection(NestedProjects) = preSolution 84 | {697DEC29-7B76-4B02-9533-FC131647034E} = {D82C9880-2134-41A3-B428-24AC5318F17E} 85 | {1012D69F-4831-4009-9600-7D347334B9DD} = {D82C9880-2134-41A3-B428-24AC5318F17E} 86 | {E0455B9C-9EEF-421E-9658-4182574195CC} = {D82C9880-2134-41A3-B428-24AC5318F17E} 87 | {51704BC7-BF0C-4403-950D-61BE77156F1C} = {D82C9880-2134-41A3-B428-24AC5318F17E} 88 | EndGlobalSection 89 | GlobalSection(ExtensibilityGlobals) = postSolution 90 | SolutionGuid = {7F80634F-BE68-4D3F-AC1B-BCC9DB70251B} 91 | EndGlobalSection 92 | EndGlobal 93 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 damienbod 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # NLog posts in this series: 3 | 4 |
    5 |
  1. ASP.NET Core logging with NLog and Microsoft SQL Server
  2. 6 |
  3. ASP.NET Core logging with NLog and Elasticsearch
  4. 7 |
  5. Settings the NLog database connection string in the ASP.NET Core appsettings.json
  6. 8 |
  7. .NET Core logging to MySQL using NLog
  8. 9 |
  9. .NET Core logging with NLog and PostgreSQL
  10. 10 | 11 |
12 | 13 | # History 14 | 15 | 2020-01-12 Updated to .NET Core 3.1, NLog.Web.AspNetCore 4.9.0 16 | 17 | 2018-04-04 Updated to .NET Core 2.0, NLog 4.5.1, and Elasticsearch Nuget package 18 | 19 | 20 | ## ASP.NET Core logging with NLog and MS SQLServer 21 | 22 | This article shows how to setup logging in an ASP.NET Core application which logs to a Microsoft SQL Server using NLog. 23 | 24 | The NLog.Web.AspNetCore Nuget package is added to the dependencies in the csproj file. 25 | 26 | ```xml 27 | 28 | 29 | 30 | netcoreapp3.1 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | PreserveNewest 48 | 49 | 50 | 51 | ``` 52 | 53 | 54 | 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. 55 | 56 | ```xml 57 | 58 | 63 | 64 | 65 | 66 | 68 | 69 | 71 | 72 | 73 | 74 | 75 | 76 | ${gdc:item=connectionString} 77 | 102 | 103 | 104 | insert into dbo.Log ( 105 | Application, Logged, Level, Message, 106 | Logger, CallSite, Exception 107 | ) values ( 108 | @Application, @Logged, @Level, @Message, 109 | @Logger, @Callsite, @Exception 110 | ); 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | ``` 137 | 138 | 139 | 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. 140 | 141 | ```sql 142 | SET ANSI_NULLS ON 143 | SET QUOTED_IDENTIFIER ON 144 | CREATE TABLE [dbo].[Log] ( 145 | [Id] [int] IDENTITY(1,1) NOT NULL, 146 | [Application] [nvarchar](50) NOT NULL, 147 | [Logged] [datetime] NOT NULL, 148 | [Level] [nvarchar](50) NOT NULL, 149 | [Message] [nvarchar](max) NOT NULL, 150 | [Logger] [nvarchar](250) NULL, 151 | [Callsite] [nvarchar](max) NULL, 152 | [Exception] [nvarchar](max) NULL, 153 | CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([Id] ASC) 154 | WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 155 | ) ON [PRIMARY] 156 | 157 | ``` 158 | 159 | 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. 160 | 161 | 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. 162 | 163 | 164 | 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. 165 | 166 | ```csharp 167 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 168 | { 169 | GlobalDiagnosticsContext.Set("configDir", "C:\\git\\damienbod\\AspNetCoreNlog\\Logs"); 170 | GlobalDiagnosticsContext.Set("connectionString", Configuration.GetConnectionString("DefaultConnection")); 171 | 172 | if (env.IsDevelopment()) 173 | { 174 | app.UseDeveloperExceptionPage(); 175 | } 176 | else 177 | { 178 | app.UseExceptionHandler("/Home/Error"); 179 | } 180 | 181 | 182 | app.UseDefaultFiles(); 183 | app.UseStaticFiles(); 184 | 185 | app.UseRouting(); 186 | 187 | app.UseEndpoints(endpoints => 188 | { 189 | endpoints.MapControllerRoute( 190 | name: "default", 191 | pattern: "{controller=Home}/{action=Index}/{id?}"); 192 | }); 193 | } 194 | 195 | ``` 196 | 197 | ```csharp 198 | using System; 199 | using System.Collections.Generic; 200 | using System.Linq; 201 | using System.Threading.Tasks; 202 | using Microsoft.AspNetCore.Hosting; 203 | using Microsoft.Extensions.Configuration; 204 | using Microsoft.Extensions.Hosting; 205 | using Microsoft.Extensions.Logging; 206 | using NLog; 207 | using NLog.Web; 208 | 209 | namespace AspNetCoreNlog 210 | { 211 | public static class Program 212 | { 213 | public static void Main(string[] args) 214 | { 215 | var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); 216 | try 217 | { 218 | logger.Debug("init main"); 219 | CreateHostBuilder(args).Build().Run(); 220 | } 221 | catch (Exception exception) 222 | { 223 | //NLog: catch setup errors 224 | logger.Error(exception, "Stopped program because of exception"); 225 | throw; 226 | } 227 | finally 228 | { 229 | // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) 230 | NLog.LogManager.Shutdown(); 231 | } 232 | } 233 | 234 | public static IHostBuilder CreateHostBuilder(string[] args) => 235 | Host.CreateDefaultBuilder(args) 236 | .ConfigureWebHostDefaults(webBuilder => 237 | { 238 | webBuilder.UseStartup(); 239 | }) 240 | .ConfigureLogging(logging => 241 | { 242 | logging.ClearProviders(); 243 | logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); 244 | }) 245 | .UseNLog(); // NLog: Setup NLog for Dependency injection 246 | } 247 | } 248 | 249 | ``` 250 | 251 | Now the logging can be used, using the default logging framework from ASP.NET Core. 252 | 253 | An example of an ActionFilter 254 | 255 | ```csharp 256 | using Microsoft.AspNetCore.Mvc.Filters; 257 | using Microsoft.Extensions.Logging; 258 | 259 | namespace AspNetCoreNlog 260 | { 261 | public class LogFilter : ActionFilterAttribute 262 | { 263 | private readonly ILogger _logger; 264 | 265 | public LogFilter(ILoggerFactory loggerFactory) 266 | { 267 | _logger = loggerFactory.CreateLogger("LogFilter"); 268 | } 269 | 270 | public override void OnActionExecuting(ActionExecutingContext context) 271 | { 272 | _logger.LogInformation("OnActionExecuting"); 273 | base.OnActionExecuting(context); 274 | } 275 | 276 | public override void OnActionExecuted(ActionExecutedContext context) 277 | { 278 | _logger.LogInformation("OnActionExecuted"); 279 | base.OnActionExecuted(context); 280 | } 281 | 282 | public override void OnResultExecuting(ResultExecutingContext context) 283 | { 284 | _logger.LogInformation("OnResultExecuting"); 285 | base.OnResultExecuting(context); 286 | } 287 | 288 | public override void OnResultExecuted(ResultExecutedContext context) 289 | { 290 | _logger.LogInformation("OnResultExecuted"); 291 | base.OnResultExecuted(context); 292 | } 293 | } 294 | } 295 | 296 | 297 | ``` 298 | 299 | The action filter is added in the Startup ConfigureServices services. 300 | 301 | ```csharp 302 | public void ConfigureServices(IServiceCollection services) 303 | { 304 | services.AddSingleton(); 305 | // Add framework services. 306 | services.AddControllers(); 307 | 308 | services.AddScoped(); 309 | } 310 | 311 | ``` 312 | 313 | And some logging can be added to a MVC controller. 314 | 315 | ```csharp 316 | using System; 317 | using System.Collections.Generic; 318 | using Microsoft.AspNetCore.Mvc; 319 | using Microsoft.Extensions.Logging; 320 | 321 | namespace AspNetCoreNlog.Controllers 322 | { 323 | [ServiceFilter(typeof(LogFilter))] 324 | [Route("api/[controller]")] 325 | public class ValuesController : Controller 326 | { 327 | private ILogger _logger; 328 | 329 | public ValuesController(ILogger logger) 330 | { 331 | _logger = logger; 332 | } 333 | 334 | [HttpGet] 335 | public IEnumerable Get() 336 | { 337 | _logger.LogCritical("nlog is working from a controller"); 338 | throw new ArgumentException("way wrong"); 339 | return new string[] { "value1", "value2" }; 340 | } 341 | 342 | ``` 343 | 344 | When the application is started, the logs are written to a local file in the Logs folder and also to the database. 345 | 346 | 347 | sqlaspnetdatabselogger_01 348 | 349 | ## Links 350 | 351 | https://github.com/NLog/NLog.Web 352 | 353 | https://github.com/NLog/NLog.Extensions.Logging 354 | 355 | https://github.com/NLog 356 | 357 | https://docs.asp.net/en/latest/fundamentals/logging.html 358 | 359 | https://msdn.microsoft.com/en-us/magazine/mt694089.aspx 360 | 361 | https://github.com/nlog/NLog/wiki/Database-target 362 | -------------------------------------------------------------------------------- /sqlaspnetdatabselogger_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/damienbod/AspNetCoreNlog/66d570e6e3600844f54cbac9d92c8599b9d41513/sqlaspnetdatabselogger_01.png -------------------------------------------------------------------------------- /src/AspNetCoreNlog/AspNetCoreNlog.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | PreserveNewest 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/AspNetCoreNlog/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.Extensions.Logging; 5 | 6 | namespace AspNetCoreNlog.Controllers 7 | { 8 | [ServiceFilter(typeof(LogFilter))] 9 | [Route("api/[controller]")] 10 | public class ValuesController : Controller 11 | { 12 | private ILogger _logger; 13 | 14 | public ValuesController(ILogger logger) 15 | { 16 | _logger = logger; 17 | } 18 | 19 | [HttpGet] 20 | public IEnumerable Get() 21 | { 22 | _logger.LogCritical("nlog is working from a controller"); 23 | throw new ArgumentException("way wrong"); 24 | return new string[] { "value1", "value2" }; 25 | } 26 | 27 | // GET api/values/5 28 | [HttpGet("{id}")] 29 | public string Get(int id) 30 | { 31 | return "value"; 32 | } 33 | 34 | // POST api/values 35 | [HttpPost] 36 | public void Post([FromBody]string value) 37 | { 38 | } 39 | 40 | // PUT api/values/5 41 | [HttpPut("{id}")] 42 | public void Put(int id, [FromBody]string value) 43 | { 44 | } 45 | 46 | // DELETE api/values/5 47 | [HttpDelete("{id}")] 48 | public void Delete(int id) 49 | { 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/AspNetCoreNlog/LogFilter.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.Filters; 2 | using Microsoft.Extensions.Logging; 3 | 4 | namespace AspNetCoreNlog 5 | { 6 | public class LogFilter : ActionFilterAttribute 7 | { 8 | private readonly ILogger _logger; 9 | 10 | public LogFilter(ILoggerFactory loggerFactory) 11 | { 12 | _logger = loggerFactory.CreateLogger("LogFilter"); 13 | } 14 | 15 | public override void OnActionExecuting(ActionExecutingContext context) 16 | { 17 | _logger.LogInformation("OnActionExecuting"); 18 | base.OnActionExecuting(context); 19 | } 20 | 21 | public override void OnActionExecuted(ActionExecutedContext context) 22 | { 23 | _logger.LogInformation("OnActionExecuted"); 24 | base.OnActionExecuted(context); 25 | } 26 | 27 | public override void OnResultExecuting(ResultExecutingContext context) 28 | { 29 | _logger.LogInformation("OnResultExecuting"); 30 | base.OnResultExecuting(context); 31 | } 32 | 33 | public override void OnResultExecuted(ResultExecutedContext context) 34 | { 35 | _logger.LogInformation("OnResultExecuted"); 36 | base.OnResultExecuted(context); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/AspNetCoreNlog/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | using NLog; 10 | using NLog.Web; 11 | 12 | namespace AspNetCoreNlog 13 | { 14 | public static class Program 15 | { 16 | public static void Main(string[] args) 17 | { 18 | var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); 19 | try 20 | { 21 | logger.Debug("init main"); 22 | CreateHostBuilder(args).Build().Run(); 23 | } 24 | catch (Exception exception) 25 | { 26 | //NLog: catch setup errors 27 | logger.Error(exception, "Stopped program because of exception"); 28 | throw; 29 | } 30 | finally 31 | { 32 | // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) 33 | NLog.LogManager.Shutdown(); 34 | } 35 | } 36 | 37 | public static IHostBuilder CreateHostBuilder(string[] args) => 38 | Host.CreateDefaultBuilder(args) 39 | .ConfigureWebHostDefaults(webBuilder => 40 | { 41 | webBuilder.UseStartup(); 42 | }) 43 | .ConfigureLogging(logging => 44 | { 45 | logging.ClearProviders(); 46 | logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); 47 | }) 48 | .UseNLog(); // NLog: Setup NLog for Dependency injection 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/AspNetCoreNlog/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "https://localhost:44334/", 7 | "sslPort": 44334 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "launchUrl": "api/values", 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "AspNetCoreNlog": { 20 | "commandName": "Project", 21 | "launchBrowser": true, 22 | "launchUrl": "http://localhost:5000/api/values", 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/AspNetCoreNlog/Startup.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Linq; 3 | using Microsoft.AspNetCore.Builder; 4 | using Microsoft.AspNetCore.Hosting; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Logging; 8 | using NLog; 9 | using NLog.Extensions.Logging; 10 | using NLog.Targets; 11 | using Microsoft.AspNetCore.Http; 12 | using NLog.Web; 13 | using Microsoft.Extensions.Hosting; 14 | 15 | namespace AspNetCoreNlog 16 | { 17 | public class Startup 18 | { 19 | public Startup(IConfiguration configuration) 20 | { 21 | Configuration = configuration; 22 | } 23 | 24 | public IConfiguration Configuration { get; } 25 | 26 | // This method gets called by the runtime. Use this method to add services to the container. 27 | public void ConfigureServices(IServiceCollection services) 28 | { 29 | services.AddSingleton(); 30 | // Add framework services. 31 | services.AddControllers(); 32 | 33 | services.AddScoped(); 34 | } 35 | 36 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 37 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 38 | { 39 | GlobalDiagnosticsContext.Set("configDir", "C:\\git\\damienbod\\AspNetCoreNlog\\Logs"); 40 | GlobalDiagnosticsContext.Set("connectionString", Configuration.GetConnectionString("DefaultConnection")); 41 | 42 | if (env.IsDevelopment()) 43 | { 44 | app.UseDeveloperExceptionPage(); 45 | } 46 | else 47 | { 48 | app.UseExceptionHandler("/Home/Error"); 49 | } 50 | 51 | 52 | app.UseDefaultFiles(); 53 | app.UseStaticFiles(); 54 | 55 | app.UseRouting(); 56 | 57 | app.UseEndpoints(endpoints => 58 | { 59 | endpoints.MapControllerRoute( 60 | name: "default", 61 | pattern: "{controller=Home}/{action=Index}/{id?}"); 62 | }); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/AspNetCoreNlog/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "LogLevel": { 5 | "Default": "Debug", 6 | "System": "Information", 7 | "Microsoft": "Information" 8 | } 9 | }, 10 | "ElasticsearchUrl": "http://localhost:9200", 11 | "ConnectionStrings": { 12 | "DefaultConnection": "Data Source=.\\SQLEXPRESS;Initial Catalog=NLogDb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/AspNetCoreNlog/nlog.config: -------------------------------------------------------------------------------- 1 |  2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 16 | 17 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | ${gdc:item=connectionString} 29 | 54 | 55 | 56 | insert into dbo.Log ( 57 | Application, Logged, Level, Message, 58 | Logger, CallSite, Exception 59 | ) values ( 60 | @Application, @Logged, @Level, @Message, 61 | @Logger, @Callsite, @Exception 62 | ); 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /src/AspNetCoreNlog/nlog.database.config: -------------------------------------------------------------------------------- 1 |  2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Data Source=N275\MSSQLSERVER2014;Initial Catalog=Nlogs;Integrated Security=True; 14 | 15 | 40 | 41 | 42 | insert into dbo.Log ( 43 | Application, Logged, Level, Message, 44 | Logger, CallSite, Exception 45 | ) values ( 46 | @Application, @Logged, @Level, @Message, 47 | @Logger, @Callsite, @Exception 48 | ); 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /src/AspNetCoreNlog/nlog.elasticsearch.config: -------------------------------------------------------------------------------- 1 |  2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/AspNetCoreNlog/nlog.file.config: -------------------------------------------------------------------------------- 1 |  2 | 7 | 8 | 9 | 11 | 12 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/AspNetCoreNlog/web.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/ConsoleNLog/ConsoleNLog.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | PreserveNewest 15 | true 16 | PreserveNewest 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | PreserveNewest 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/ConsoleNLog/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using NLog; 3 | 4 | namespace ConsoleNLog 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | GlobalDiagnosticsContext.Set("configDir", "C:\\git\\damienbod\\AspNetCoreNlog\\Logs"); 11 | GlobalDiagnosticsContext.Set("connectionString", "Data Source=.\\SQLEXPRESS;Initial Catalog=NLogDb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"); 12 | 13 | var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); 14 | logger.Warn("console logging is great"); 15 | 16 | Console.WriteLine("log sent"); 17 | Console.ReadKey(); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/ConsoleNLog/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "LogLevel": { 5 | "Default": "Debug", 6 | "System": "Information", 7 | "Microsoft": "Information" 8 | } 9 | }, 10 | "ElasticsearchUrl": "http://localhost:9200", 11 | "ConnectionStrings": { 12 | "DefaultConnection": "Data Source=.\\SQLEXPRESS;Initial Catalog=NLogDb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/ConsoleNLog/nlog.config: -------------------------------------------------------------------------------- 1 |  2 | 7 | 8 | 9 | 10 | 12 | 13 | 15 | 16 | 17 | 18 | 19 | 20 | ${gdc:item=connectionString} 21 | 46 | 47 | 48 | insert into dbo.Log ( 49 | Application, Logged, Level, Message, 50 | Logger, CallSite, Exception 51 | ) values ( 52 | @Application, @Logged, @Level, @Message, 53 | @Logger, @Callsite, @Exception 54 | ); 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /src/ConsoleNLogMySQL/ConsoleNLogMySQL.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | PreserveNewest 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/ConsoleNLogMySQL/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using NLog; 6 | using NLog.Targets; 7 | 8 | namespace ConsoleNLog 9 | { 10 | public class Program 11 | { 12 | public static void Main(string[] args) 13 | { 14 | GlobalDiagnosticsContext.Set("configDir", "C:\\git\\damienbod\\AspNetCoreNlog\\Logs"); 15 | GlobalDiagnosticsContext.Set("connectionString", "server=localhost;Database=nlog;user id=damienbod;password=1234;SslMode=none"); 16 | 17 | var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); 18 | 19 | logger.Warn("console logging is great"); 20 | 21 | Console.WriteLine("log sent"); 22 | Console.ReadKey(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/ConsoleNLogMySQL/nlog.config: -------------------------------------------------------------------------------- 1 |  2 | 7 | 8 | 9 | 11 | 12 | 14 | 15 | 16 | 17 | 21 | 22 | 37 | 38 | 39 | insert into nlog.log ( 40 | Application, Logged, Level, Message, 41 | Logger, CallSite, Exception 42 | ) values ( 43 | @Application, @Logged, @Level, @Message, 44 | @Logger, @Callsite, @Exception 45 | ); 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /src/ConsoleNLogPostgreSQL/ConsoleNLogPostgreSQL.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | PreserveNewest 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/ConsoleNLogPostgreSQL/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using NLog; 3 | 4 | namespace ConsoleNLogPostgreSQL 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | GlobalDiagnosticsContext.Set("configDir", "C:\\git\\damienbod\\AspNetCoreNlog\\Logs"); 11 | GlobalDiagnosticsContext.Set("connectionString", "User ID=damienbod;Password=damienbod;Host=localhost;Port=5432;Database=log;Pooling=true;"); 12 | 13 | var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); 14 | 15 | logger.Warn("console logging is great"); 16 | logger.Error(new ArgumentException("oh no")); 17 | Console.WriteLine("log sent"); 18 | Console.ReadKey(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/ConsoleNLogPostgreSQL/nlog.config: -------------------------------------------------------------------------------- 1 |  2 | 7 | 8 | 9 | 11 | 12 | 14 | 15 | 16 | 17 | 21 | 22 | 39 | 40 | 41 | insert into logs ( 42 | Application, Logged, Level, Message, 43 | Logger, CallSite, Exception 44 | ) values ( 45 | @Application, @Logged, @Level, @Message, 46 | @Logger, @Callsite, @Exception 47 | ); 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | --------------------------------------------------------------------------------