From e41f77f39d67686a8d3a433981bd528bf037dc15 Mon Sep 17 00:00:00 2001 From: Nicholas Blumhardt Date: Tue, 5 Sep 2017 12:22:26 +1000 Subject: [PATCH 1/8] Dev version bump [Skip CI] --- src/Serilog.AspNetCore/Serilog.AspNetCore.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj b/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj index f029249..81ab8c5 100644 --- a/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj +++ b/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj @@ -2,7 +2,7 @@ Serilog support for ASP.NET Core logging - 2.0.0 + 2.0.1 Microsoft;Serilog Contributors netstandard2.0 true From 5e591095695bda18643ac444bc4f855e016e6038 Mon Sep 17 00:00:00 2001 From: Nicholas Blumhardt Date: Mon, 9 Oct 2017 11:56:32 +1000 Subject: [PATCH 2/8] Link to the `SerilogMiddleware` sample [Skip CI] --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index f14822a..5f06ff4 100644 --- a/README.md +++ b/README.md @@ -86,3 +86,5 @@ Tip: to see Serilog output in the Visual Studio output window when running under ### Using the package With _Serilog.AspNetCore_ installed and configured, you can write log messages directly through Serilog or any `ILogger` interface injected by ASP.NET. All loggers will use the same underlying implementation, levels, and destinations. + +**Tip:** change the minimum level for `Microsoft` to `Warning` and plug in this [custom logging middleware](https://github.com/datalust/serilog-middleware-example/blob/master/src/Datalust.SerilogMiddlewareExample/Diagnostics/SerilogMiddleware.cs) to clean up request logging output and record more context around errors and exceptions. From 76ebdb093f964621ae4cc6a8bd6240f3a8256d6b Mon Sep 17 00:00:00 2001 From: GoldenCrystal Date: Wed, 30 Aug 2017 23:34:39 +0200 Subject: [PATCH 3/8] Add an overload to UseSerilog() - Useful for configuring Serilog during the construction of IWebHost. --- .../Controllers/ConfigurationController.cs | 55 +++++++++++++++++++ samples/SimpleWebSampleV2/Program.cs | 42 ++++++++++++++ .../Properties/launchSettings.json | 29 ++++++++++ .../SimpleWebSampleV2.csproj | 16 ++++++ samples/SimpleWebSampleV2/Startup.cs | 35 ++++++++++++ .../appsettings.Development.json | 7 +++ samples/SimpleWebSampleV2/appsettings.json | 12 ++++ serilog-aspnetcore.sln | 9 ++- .../SerilogWebHostBuilderExtensions.cs | 20 +++++++ 9 files changed, 224 insertions(+), 1 deletion(-) create mode 100644 samples/SimpleWebSampleV2/Controllers/ConfigurationController.cs create mode 100644 samples/SimpleWebSampleV2/Program.cs create mode 100644 samples/SimpleWebSampleV2/Properties/launchSettings.json create mode 100644 samples/SimpleWebSampleV2/SimpleWebSampleV2.csproj create mode 100644 samples/SimpleWebSampleV2/Startup.cs create mode 100644 samples/SimpleWebSampleV2/appsettings.Development.json create mode 100644 samples/SimpleWebSampleV2/appsettings.json diff --git a/samples/SimpleWebSampleV2/Controllers/ConfigurationController.cs b/samples/SimpleWebSampleV2/Controllers/ConfigurationController.cs new file mode 100644 index 0000000..69137a7 --- /dev/null +++ b/samples/SimpleWebSampleV2/Controllers/ConfigurationController.cs @@ -0,0 +1,55 @@ +// Copyright 2017 Serilog Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; + +namespace SimpleWebSampleV2.Controllers +{ + // This controller lists configuration settings and their value. + // Please, do try to update the appsettings.json while the application is running. 😉 + + [Route("api/[controller]")] + public class ConfigurationController : Controller + { + public ConfigurationController(IConfiguration configuration, ILogger logger) + { + Configuration = configuration; + Logger = logger; + } + + public IConfiguration Configuration { get; } + public ILogger Logger { get; } + + [HttpGet] + public IEnumerable> Get() + { + Logger.LogInformation("Listing all configuration settings…"); + + return Configuration.AsEnumerable(); + } + + [HttpGet("{key}")] + public string Get(string key) + { + Logger.LogInformation("The configuration key {ConfigurationKey} was requested.", key); + string value = Configuration[key]; + Logger.LogInformation("The configuration key {ConfigurationKey} has value {ConfigurationValue}.", key, value); + + return value; + } + } +} diff --git a/samples/SimpleWebSampleV2/Program.cs b/samples/SimpleWebSampleV2/Program.cs new file mode 100644 index 0000000..ed7a503 --- /dev/null +++ b/samples/SimpleWebSampleV2/Program.cs @@ -0,0 +1,42 @@ +using System; +using System.IO; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Serilog; + +namespace SimpleWebSampleV2 +{ + public class Program + { + public static void Main(string[] args) + { + var host = new WebHostBuilder() + .UseKestrel() + .UseContentRoot(Directory.GetCurrentDirectory()) + .ConfigureAppConfiguration + ( + // Load the application configuration over the web host configuration. + (hostingContext, configurationBuilder) => + { + configurationBuilder + .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) + .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) + .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true) + .AddEnvironmentVariables(); + } + ) + .UseSerilog + ( + // Configure Serilog to be used as the logger for the whole application. + (hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration) + .Enrich.FromLogContext() + .WriteTo.Console() + ) + .UseIISIntegration() + .UseStartup() + .Build(); + + host.Run(); + } + } +} diff --git a/samples/SimpleWebSampleV2/Properties/launchSettings.json b/samples/SimpleWebSampleV2/Properties/launchSettings.json new file mode 100644 index 0000000..a3496b4 --- /dev/null +++ b/samples/SimpleWebSampleV2/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:52009/", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "api/configuration/Greeting", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "SimpleWebSample": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "api/configuration/Greeting", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "http://localhost:52010/" + } + } +} \ No newline at end of file diff --git a/samples/SimpleWebSampleV2/SimpleWebSampleV2.csproj b/samples/SimpleWebSampleV2/SimpleWebSampleV2.csproj new file mode 100644 index 0000000..24c931b --- /dev/null +++ b/samples/SimpleWebSampleV2/SimpleWebSampleV2.csproj @@ -0,0 +1,16 @@ + + + netcoreapp2.0 + + + + + + + + + + + + + diff --git a/samples/SimpleWebSampleV2/Startup.cs b/samples/SimpleWebSampleV2/Startup.cs new file mode 100644 index 0000000..5507389 --- /dev/null +++ b/samples/SimpleWebSampleV2/Startup.cs @@ -0,0 +1,35 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace SimpleWebSampleV2 +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddMvc(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IHostingEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseMvc(); + } + } +} diff --git a/samples/SimpleWebSampleV2/appsettings.Development.json b/samples/SimpleWebSampleV2/appsettings.Development.json new file mode 100644 index 0000000..a96c927 --- /dev/null +++ b/samples/SimpleWebSampleV2/appsettings.Development.json @@ -0,0 +1,7 @@ +{ + "Serilog": { + "MinimumLevel": { + "Default": "Debug" + } + } +} diff --git a/samples/SimpleWebSampleV2/appsettings.json b/samples/SimpleWebSampleV2/appsettings.json new file mode 100644 index 0000000..416e281 --- /dev/null +++ b/samples/SimpleWebSampleV2/appsettings.json @@ -0,0 +1,12 @@ +{ + "Serilog": { + "MinimumLevel": { + "Default": "Debug", + "Override": { + "Microsoft": "Warning", + "System": "Warning" + } + } + }, + "Greeting": "Hello World !" +} diff --git a/serilog-aspnetcore.sln b/serilog-aspnetcore.sln index 3957472..e32ce36 100644 --- a/serilog-aspnetcore.sln +++ b/serilog-aspnetcore.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 -VisualStudioVersion = 15.0.26730.10 +VisualStudioVersion = 15.0.26730.12 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A1893BD1-333D-4DFE-A0F0-DDBB2FE526E0}" EndProject @@ -24,6 +24,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.AspNetCore", "src\S EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.AspNetCore.Tests", "test\Serilog.AspNetCore.Tests\Serilog.AspNetCore.Tests.csproj", "{AD51759B-CD58-473F-9620-0B0E56A123A1}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleWebSampleV2", "samples\SimpleWebSampleV2\SimpleWebSampleV2.csproj", "{2711EC78-7F7D-440B-A8AB-BA3D32227667}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -42,6 +44,10 @@ Global {AD51759B-CD58-473F-9620-0B0E56A123A1}.Debug|Any CPU.Build.0 = Debug|Any CPU {AD51759B-CD58-473F-9620-0B0E56A123A1}.Release|Any CPU.ActiveCfg = Release|Any CPU {AD51759B-CD58-473F-9620-0B0E56A123A1}.Release|Any CPU.Build.0 = Release|Any CPU + {2711EC78-7F7D-440B-A8AB-BA3D32227667}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2711EC78-7F7D-440B-A8AB-BA3D32227667}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2711EC78-7F7D-440B-A8AB-BA3D32227667}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2711EC78-7F7D-440B-A8AB-BA3D32227667}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -50,6 +56,7 @@ Global {69F9A0ED-7910-4F33-8919-28BB05376FBC} = {F2407211-6043-439C-8E06-3641634332E7} {0549D23F-986B-4FB2-BACE-16FD7A7BC9EF} = {A1893BD1-333D-4DFE-A0F0-DDBB2FE526E0} {AD51759B-CD58-473F-9620-0B0E56A123A1} = {E30F638E-BBBE-4AD1-93CE-48CC69CFEFE1} + {2711EC78-7F7D-440B-A8AB-BA3D32227667} = {F2407211-6043-439C-8E06-3641634332E7} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {811E61C5-3871-4633-AFAE-B35B619C8A10} diff --git a/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs b/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs index c7a1df1..c4d74b4 100644 --- a/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs +++ b/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs @@ -41,5 +41,25 @@ public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Serilog.I collection.AddSingleton(new SerilogLoggerFactory(logger, dispose))); return builder; } + + /// Sets Serilog as the logging provider. + /// The web host builder to configure. + /// The delegate for configuring the that will be used to construct a . + /// The web host builder. + public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Action configureSerilog) + { + if (builder == null) throw new ArgumentNullException(nameof(builder)); + if (configureSerilog == null) throw new ArgumentNullException(nameof(configureSerilog)); + builder.ConfigureServices + ( + (context, collection) => + { + var loggerConfiguration = new LoggerConfiguration(); + configureSerilog(context, loggerConfiguration); + collection.AddSingleton(new SerilogLoggerFactory(loggerConfiguration.CreateLogger(), true)); + } + ); + return builder; + } } } From 91d3eeede34ffeffb994f49ffb983f14d36e739f Mon Sep 17 00:00:00 2001 From: GoldenCrystal Date: Sun, 15 Oct 2017 22:37:21 +0200 Subject: [PATCH 4/8] Set Log.Logger in the new UseSerilog() overload. --- README.md | 39 +++++++++++++ .../Controllers/ConfigurationController.cs | 55 ------------------- samples/SimpleWebSampleV2/Program.cs | 42 -------------- .../Properties/launchSettings.json | 29 ---------- .../SimpleWebSampleV2.csproj | 16 ------ samples/SimpleWebSampleV2/Startup.cs | 35 ------------ .../appsettings.Development.json | 7 --- samples/SimpleWebSampleV2/appsettings.json | 12 ---- serilog-aspnetcore.sln | 7 --- .../SerilogWebHostBuilderExtensions.cs | 30 +++++----- 10 files changed, 56 insertions(+), 216 deletions(-) delete mode 100644 samples/SimpleWebSampleV2/Controllers/ConfigurationController.cs delete mode 100644 samples/SimpleWebSampleV2/Program.cs delete mode 100644 samples/SimpleWebSampleV2/Properties/launchSettings.json delete mode 100644 samples/SimpleWebSampleV2/SimpleWebSampleV2.csproj delete mode 100644 samples/SimpleWebSampleV2/Startup.cs delete mode 100644 samples/SimpleWebSampleV2/appsettings.Development.json delete mode 100644 samples/SimpleWebSampleV2/appsettings.json diff --git a/README.md b/README.md index 5f06ff4..6ac3b6f 100644 --- a/README.md +++ b/README.md @@ -88,3 +88,42 @@ Tip: to see Serilog output in the Visual Studio output window when running under With _Serilog.AspNetCore_ installed and configured, you can write log messages directly through Serilog or any `ILogger` interface injected by ASP.NET. All loggers will use the same underlying implementation, levels, and destinations. **Tip:** change the minimum level for `Microsoft` to `Warning` and plug in this [custom logging middleware](https://github.com/datalust/serilog-middleware-example/blob/master/src/Datalust.SerilogMiddlewareExample/Diagnostics/SerilogMiddleware.cs) to clean up request logging output and record more context around errors and exceptions. + +### Alternative configuration + +You can chose to build the logger as part of the `WebHostBuilder` pipeline, and thus benefit from the application configuration. +The following code shows an example of such a configuration: + +````csharp +public class Program +{ + public static void Main(string[] args) + { + var host = new WebHostBuilder() + .UseKestrel() + .UseContentRoot(Directory.GetCurrentDirectory()) + // Load the application configuration over the web host configuration. + .ConfigureAppConfiguration((hostingContext, configurationBuilder) => + { + configurationBuilder + .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) + .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) + .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true) + .AddEnvironmentVariables(); + }) + // Configure Serilog to be used as the logger for the whole application. + .UseSerilog((hostingContext, loggerConfiguration) => + loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration) + .Enrich.FromLogContext() + .WriteTo.Console() + ) + .UseIISIntegration() + .UseStartup() + .Build(); + + host.Run(); + } +} +```` + +With this code, the default behavior is to set the created `ILogger` as the default logger. `Log.Logger` can be used as usual to access the created logger. diff --git a/samples/SimpleWebSampleV2/Controllers/ConfigurationController.cs b/samples/SimpleWebSampleV2/Controllers/ConfigurationController.cs deleted file mode 100644 index 69137a7..0000000 --- a/samples/SimpleWebSampleV2/Controllers/ConfigurationController.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2017 Serilog Contributors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using System.Collections.Generic; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; - -namespace SimpleWebSampleV2.Controllers -{ - // This controller lists configuration settings and their value. - // Please, do try to update the appsettings.json while the application is running. 😉 - - [Route("api/[controller]")] - public class ConfigurationController : Controller - { - public ConfigurationController(IConfiguration configuration, ILogger logger) - { - Configuration = configuration; - Logger = logger; - } - - public IConfiguration Configuration { get; } - public ILogger Logger { get; } - - [HttpGet] - public IEnumerable> Get() - { - Logger.LogInformation("Listing all configuration settings…"); - - return Configuration.AsEnumerable(); - } - - [HttpGet("{key}")] - public string Get(string key) - { - Logger.LogInformation("The configuration key {ConfigurationKey} was requested.", key); - string value = Configuration[key]; - Logger.LogInformation("The configuration key {ConfigurationKey} has value {ConfigurationValue}.", key, value); - - return value; - } - } -} diff --git a/samples/SimpleWebSampleV2/Program.cs b/samples/SimpleWebSampleV2/Program.cs deleted file mode 100644 index ed7a503..0000000 --- a/samples/SimpleWebSampleV2/Program.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.IO; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Serilog; - -namespace SimpleWebSampleV2 -{ - public class Program - { - public static void Main(string[] args) - { - var host = new WebHostBuilder() - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .ConfigureAppConfiguration - ( - // Load the application configuration over the web host configuration. - (hostingContext, configurationBuilder) => - { - configurationBuilder - .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) - .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) - .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true) - .AddEnvironmentVariables(); - } - ) - .UseSerilog - ( - // Configure Serilog to be used as the logger for the whole application. - (hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration) - .Enrich.FromLogContext() - .WriteTo.Console() - ) - .UseIISIntegration() - .UseStartup() - .Build(); - - host.Run(); - } - } -} diff --git a/samples/SimpleWebSampleV2/Properties/launchSettings.json b/samples/SimpleWebSampleV2/Properties/launchSettings.json deleted file mode 100644 index a3496b4..0000000 --- a/samples/SimpleWebSampleV2/Properties/launchSettings.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:52009/", - "sslPort": 0 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "api/configuration/Greeting", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "SimpleWebSample": { - "commandName": "Project", - "launchBrowser": true, - "launchUrl": "api/configuration/Greeting", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "http://localhost:52010/" - } - } -} \ No newline at end of file diff --git a/samples/SimpleWebSampleV2/SimpleWebSampleV2.csproj b/samples/SimpleWebSampleV2/SimpleWebSampleV2.csproj deleted file mode 100644 index 24c931b..0000000 --- a/samples/SimpleWebSampleV2/SimpleWebSampleV2.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - netcoreapp2.0 - - - - - - - - - - - - - diff --git a/samples/SimpleWebSampleV2/Startup.cs b/samples/SimpleWebSampleV2/Startup.cs deleted file mode 100644 index 5507389..0000000 --- a/samples/SimpleWebSampleV2/Startup.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace SimpleWebSampleV2 -{ - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - services.AddMvc(); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - - app.UseMvc(); - } - } -} diff --git a/samples/SimpleWebSampleV2/appsettings.Development.json b/samples/SimpleWebSampleV2/appsettings.Development.json deleted file mode 100644 index a96c927..0000000 --- a/samples/SimpleWebSampleV2/appsettings.Development.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "Serilog": { - "MinimumLevel": { - "Default": "Debug" - } - } -} diff --git a/samples/SimpleWebSampleV2/appsettings.json b/samples/SimpleWebSampleV2/appsettings.json deleted file mode 100644 index 416e281..0000000 --- a/samples/SimpleWebSampleV2/appsettings.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "Serilog": { - "MinimumLevel": { - "Default": "Debug", - "Override": { - "Microsoft": "Warning", - "System": "Warning" - } - } - }, - "Greeting": "Hello World !" -} diff --git a/serilog-aspnetcore.sln b/serilog-aspnetcore.sln index e32ce36..e7f7ca0 100644 --- a/serilog-aspnetcore.sln +++ b/serilog-aspnetcore.sln @@ -24,8 +24,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.AspNetCore", "src\S EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.AspNetCore.Tests", "test\Serilog.AspNetCore.Tests\Serilog.AspNetCore.Tests.csproj", "{AD51759B-CD58-473F-9620-0B0E56A123A1}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleWebSampleV2", "samples\SimpleWebSampleV2\SimpleWebSampleV2.csproj", "{2711EC78-7F7D-440B-A8AB-BA3D32227667}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -44,10 +42,6 @@ Global {AD51759B-CD58-473F-9620-0B0E56A123A1}.Debug|Any CPU.Build.0 = Debug|Any CPU {AD51759B-CD58-473F-9620-0B0E56A123A1}.Release|Any CPU.ActiveCfg = Release|Any CPU {AD51759B-CD58-473F-9620-0B0E56A123A1}.Release|Any CPU.Build.0 = Release|Any CPU - {2711EC78-7F7D-440B-A8AB-BA3D32227667}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2711EC78-7F7D-440B-A8AB-BA3D32227667}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2711EC78-7F7D-440B-A8AB-BA3D32227667}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2711EC78-7F7D-440B-A8AB-BA3D32227667}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -56,7 +50,6 @@ Global {69F9A0ED-7910-4F33-8919-28BB05376FBC} = {F2407211-6043-439C-8E06-3641634332E7} {0549D23F-986B-4FB2-BACE-16FD7A7BC9EF} = {A1893BD1-333D-4DFE-A0F0-DDBB2FE526E0} {AD51759B-CD58-473F-9620-0B0E56A123A1} = {E30F638E-BBBE-4AD1-93CE-48CC69CFEFE1} - {2711EC78-7F7D-440B-A8AB-BA3D32227667} = {F2407211-6043-439C-8E06-3641634332E7} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {811E61C5-3871-4633-AFAE-B35B619C8A10} diff --git a/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs b/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs index c4d74b4..0acbb71 100644 --- a/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs +++ b/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs @@ -38,27 +38,31 @@ public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Serilog.I { if (builder == null) throw new ArgumentNullException(nameof(builder)); builder.ConfigureServices(collection => - collection.AddSingleton(new SerilogLoggerFactory(logger, dispose))); + collection.AddSingleton(services => new SerilogLoggerFactory(logger, dispose))); return builder; } /// Sets Serilog as the logging provider. + /// + /// A is supplied so that configuration and hosting information can be used. + /// The logger will be shut down when application services are disposed. + /// /// The web host builder to configure. - /// The delegate for configuring the that will be used to construct a . + /// The delegate for configuring the that will be used to construct a . + /// Indicates whether to preserve the value of . /// The web host builder. - public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Action configureSerilog) + public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Action configureLogger, bool preserveStaticLogger = false) { if (builder == null) throw new ArgumentNullException(nameof(builder)); - if (configureSerilog == null) throw new ArgumentNullException(nameof(configureSerilog)); - builder.ConfigureServices - ( - (context, collection) => - { - var loggerConfiguration = new LoggerConfiguration(); - configureSerilog(context, loggerConfiguration); - collection.AddSingleton(new SerilogLoggerFactory(loggerConfiguration.CreateLogger(), true)); - } - ); + if (configureLogger == null) throw new ArgumentNullException(nameof(configureLogger)); + builder.ConfigureServices((context, collection) => + { + var loggerConfiguration = new LoggerConfiguration(); + configureLogger(context, loggerConfiguration); + var logger = loggerConfiguration.CreateLogger(); + collection.AddSingleton(services => new SerilogLoggerFactory(logger, true)); + if (!preserveStaticLogger) Log.Logger = logger; + }); return builder; } } From 79b7b1e9c7c97e106b493daa4a2a8007b72e05b2 Mon Sep 17 00:00:00 2001 From: Nicholas Blumhardt Date: Mon, 16 Oct 2017 10:59:37 +1000 Subject: [PATCH 5/8] Pass `null` to `SerilogLoggerFactory` when using static logger --- .../SerilogWebHostBuilderExtensions.cs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs b/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs index 0acbb71..f15d9c2 100644 --- a/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs +++ b/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs @@ -60,8 +60,17 @@ public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Action(services => new SerilogLoggerFactory(logger, true)); - if (!preserveStaticLogger) Log.Logger = logger; + if (preserveStaticLogger) + { + collection.AddSingleton(services => new SerilogLoggerFactory(logger, true)); + } + else + { + // Passing a `null` logger to `SerilogLoggerFactory` results in disposal via + // `Log.CloseAndFlush()`, which additionally replaces the static logger with a no-op. + Log.Logger = logger; + collection.AddSingleton(services => new SerilogLoggerFactory(null, true)); + } }); return builder; } From a04f096e3ba6679e2b1bb6c0bd290b91ffac73e8 Mon Sep 17 00:00:00 2001 From: Nicholas Blumhardt Date: Mon, 16 Oct 2017 11:05:45 +1000 Subject: [PATCH 6/8] Condense the alternative configuration example in the README [Skip CI] --- README.md | 46 +++++++++++----------------------------------- 1 file changed, 11 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 6ac3b6f..b4325cd 100644 --- a/README.md +++ b/README.md @@ -89,41 +89,17 @@ With _Serilog.AspNetCore_ installed and configured, you can write log messages d **Tip:** change the minimum level for `Microsoft` to `Warning` and plug in this [custom logging middleware](https://github.com/datalust/serilog-middleware-example/blob/master/src/Datalust.SerilogMiddlewareExample/Diagnostics/SerilogMiddleware.cs) to clean up request logging output and record more context around errors and exceptions. -### Alternative configuration +### Inline initialization -You can chose to build the logger as part of the `WebHostBuilder` pipeline, and thus benefit from the application configuration. -The following code shows an example of such a configuration: +You can alternatively configure Serilog using a delegate as shown below: -````csharp -public class Program -{ - public static void Main(string[] args) - { - var host = new WebHostBuilder() - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - // Load the application configuration over the web host configuration. - .ConfigureAppConfiguration((hostingContext, configurationBuilder) => - { - configurationBuilder - .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) - .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) - .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true) - .AddEnvironmentVariables(); - }) - // Configure Serilog to be used as the logger for the whole application. - .UseSerilog((hostingContext, loggerConfiguration) => - loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration) - .Enrich.FromLogContext() - .WriteTo.Console() - ) - .UseIISIntegration() - .UseStartup() - .Build(); - - host.Run(); - } -} -```` +```csharp + .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration + .ReadFrom.Configuration(hostingContext.Configuration) + .Enrich.FromLogContext() + .WriteTo.Console()) +``` + +This has the advantage of making the `hostingContext`'s `Configuration` object available for configuration of the logger, but at the expense of recording `Exception`s raised earlier in program startup. -With this code, the default behavior is to set the created `ILogger` as the default logger. `Log.Logger` can be used as usual to access the created logger. +If this method is used, `Log.Logger` is assigned implicitly, and closed when the app is shut down. From e5031e9af76d2772ba4e54fe7093acd726d205f2 Mon Sep 17 00:00:00 2001 From: Nicholas Blumhardt Date: Mon, 16 Oct 2017 11:29:27 +1000 Subject: [PATCH 7/8] New overload has been added; bump minor version --- src/Serilog.AspNetCore/Serilog.AspNetCore.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj b/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj index 81ab8c5..2afb7c4 100644 --- a/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj +++ b/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj @@ -2,7 +2,7 @@ Serilog support for ASP.NET Core logging - 2.0.1 + 2.1.0 Microsoft;Serilog Contributors netstandard2.0 true From 843a56954581dffb774206db89bd06b4b72fa447 Mon Sep 17 00:00:00 2001 From: Nicholas Blumhardt Date: Mon, 23 Oct 2017 08:47:20 +1000 Subject: [PATCH 8/8] #10 - keep `BuildWebHost()` in example code [Skip CI] --- README.md | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index b4325cd..dab72e6 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Install-Package Serilog.AspNetCore -DependencyVersion Highest Install-Package Serilog.Sinks.Console ``` -**Next**, in your application's _Program.cs_ file, configure Serilog first: +**Next**, in your application's _Program.cs_ file, configure Serilog first. A `try`/`catch` block will ensure any configuration issues are appropriately logged: ```csharp public class Program @@ -25,25 +25,11 @@ public class Program .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger(); -``` - -Then, add `UseSerilog()` to the web host builder. A `try`/`catch` block will ensure any configuration issues are appropriately logged: -```csharp try { Log.Information("Starting web host"); - - var host = new WebHostBuilder() - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseStartup() - .UseSerilog() // <-- Add this line - .Build(); - - host.Run(); - + BuildWebHost(args).Run(); return 0; } catch (Exception ex) @@ -56,6 +42,16 @@ Then, add `UseSerilog()` to the web host builder. A `try`/`catch` block will ens Log.CloseAndFlush(); } } +``` + +Then, add `UseSerilog()` to the web host builder in `BuildWebHost()`. + +```csharp + public static IWebHost BuildWebHost(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup() + .UseSerilog() // <-- Add this line + .Build(); } ``` @@ -83,6 +79,8 @@ That's it! With the level bumped up a little you will see log output like: Tip: to see Serilog output in the Visual Studio output window when running under IIS, select _ASP.NET Core Web Server_ from the _Show output from_ drop-down list. +A more complete example, showing _appsettings.json_ configuration, can be found in [the sample project here](https://github.com/serilog/serilog-aspnetcore/tree/dev/samples/SimpleWebSample). + ### Using the package With _Serilog.AspNetCore_ installed and configured, you can write log messages directly through Serilog or any `ILogger` interface injected by ASP.NET. All loggers will use the same underlying implementation, levels, and destinations.