diff --git a/README.md b/README.md index f14822a..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,25 @@ 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. + +**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. + +### Inline initialization + +You can alternatively configure Serilog using a delegate as shown below: + +```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. + +If this method is used, `Log.Logger` is assigned implicitly, and closed when the app is shut down. diff --git a/serilog-aspnetcore.sln b/serilog-aspnetcore.sln index 3957472..e7f7ca0 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 diff --git a/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj b/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj index f029249..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.0 + 2.1.0 Microsoft;Serilog Contributors netstandard2.0 true diff --git a/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs b/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs index c7a1df1..f15d9c2 100644 --- a/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs +++ b/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs @@ -38,7 +38,40 @@ 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 . + /// Indicates whether to preserve the value of . + /// The web host builder. + public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Action configureLogger, bool preserveStaticLogger = false) + { + if (builder == null) throw new ArgumentNullException(nameof(builder)); + if (configureLogger == null) throw new ArgumentNullException(nameof(configureLogger)); + builder.ConfigureServices((context, collection) => + { + var loggerConfiguration = new LoggerConfiguration(); + configureLogger(context, loggerConfiguration); + var logger = loggerConfiguration.CreateLogger(); + 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; } }