Skip to content

Commit 91d3eee

Browse files
committed
Set Log.Logger in the new UseSerilog() overload.
1 parent 76ebdb0 commit 91d3eee

File tree

10 files changed

+56
-216
lines changed

10 files changed

+56
-216
lines changed

README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,3 +88,42 @@ Tip: to see Serilog output in the Visual Studio output window when running under
8888
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.
8989

9090
**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.
91+
92+
### Alternative configuration
93+
94+
You can chose to build the logger as part of the `WebHostBuilder` pipeline, and thus benefit from the application configuration.
95+
The following code shows an example of such a configuration:
96+
97+
````csharp
98+
public class Program
99+
{
100+
public static void Main(string[] args)
101+
{
102+
var host = new WebHostBuilder()
103+
.UseKestrel()
104+
.UseContentRoot(Directory.GetCurrentDirectory())
105+
// Load the application configuration over the web host configuration.
106+
.ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
107+
{
108+
configurationBuilder
109+
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
110+
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
111+
.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
112+
.AddEnvironmentVariables();
113+
})
114+
// Configure Serilog to be used as the logger for the whole application.
115+
.UseSerilog((hostingContext, loggerConfiguration) =>
116+
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
117+
.Enrich.FromLogContext()
118+
.WriteTo.Console()
119+
)
120+
.UseIISIntegration()
121+
.UseStartup<Startup>()
122+
.Build();
123+
124+
host.Run();
125+
}
126+
}
127+
````
128+
129+
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.

samples/SimpleWebSampleV2/Controllers/ConfigurationController.cs

Lines changed: 0 additions & 55 deletions
This file was deleted.

samples/SimpleWebSampleV2/Program.cs

Lines changed: 0 additions & 42 deletions
This file was deleted.

samples/SimpleWebSampleV2/Properties/launchSettings.json

Lines changed: 0 additions & 29 deletions
This file was deleted.

samples/SimpleWebSampleV2/SimpleWebSampleV2.csproj

Lines changed: 0 additions & 16 deletions
This file was deleted.

samples/SimpleWebSampleV2/Startup.cs

Lines changed: 0 additions & 35 deletions
This file was deleted.

samples/SimpleWebSampleV2/appsettings.Development.json

Lines changed: 0 additions & 7 deletions
This file was deleted.

samples/SimpleWebSampleV2/appsettings.json

Lines changed: 0 additions & 12 deletions
This file was deleted.

serilog-aspnetcore.sln

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.AspNetCore", "src\S
2424
EndProject
2525
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.AspNetCore.Tests", "test\Serilog.AspNetCore.Tests\Serilog.AspNetCore.Tests.csproj", "{AD51759B-CD58-473F-9620-0B0E56A123A1}"
2626
EndProject
27-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleWebSampleV2", "samples\SimpleWebSampleV2\SimpleWebSampleV2.csproj", "{2711EC78-7F7D-440B-A8AB-BA3D32227667}"
28-
EndProject
2927
Global
3028
GlobalSection(SolutionConfigurationPlatforms) = preSolution
3129
Debug|Any CPU = Debug|Any CPU
@@ -44,10 +42,6 @@ Global
4442
{AD51759B-CD58-473F-9620-0B0E56A123A1}.Debug|Any CPU.Build.0 = Debug|Any CPU
4543
{AD51759B-CD58-473F-9620-0B0E56A123A1}.Release|Any CPU.ActiveCfg = Release|Any CPU
4644
{AD51759B-CD58-473F-9620-0B0E56A123A1}.Release|Any CPU.Build.0 = Release|Any CPU
47-
{2711EC78-7F7D-440B-A8AB-BA3D32227667}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
48-
{2711EC78-7F7D-440B-A8AB-BA3D32227667}.Debug|Any CPU.Build.0 = Debug|Any CPU
49-
{2711EC78-7F7D-440B-A8AB-BA3D32227667}.Release|Any CPU.ActiveCfg = Release|Any CPU
50-
{2711EC78-7F7D-440B-A8AB-BA3D32227667}.Release|Any CPU.Build.0 = Release|Any CPU
5145
EndGlobalSection
5246
GlobalSection(SolutionProperties) = preSolution
5347
HideSolutionNode = FALSE
@@ -56,7 +50,6 @@ Global
5650
{69F9A0ED-7910-4F33-8919-28BB05376FBC} = {F2407211-6043-439C-8E06-3641634332E7}
5751
{0549D23F-986B-4FB2-BACE-16FD7A7BC9EF} = {A1893BD1-333D-4DFE-A0F0-DDBB2FE526E0}
5852
{AD51759B-CD58-473F-9620-0B0E56A123A1} = {E30F638E-BBBE-4AD1-93CE-48CC69CFEFE1}
59-
{2711EC78-7F7D-440B-A8AB-BA3D32227667} = {F2407211-6043-439C-8E06-3641634332E7}
6053
EndGlobalSection
6154
GlobalSection(ExtensibilityGlobals) = postSolution
6255
SolutionGuid = {811E61C5-3871-4633-AFAE-B35B619C8A10}

src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -38,27 +38,31 @@ public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Serilog.I
3838
{
3939
if (builder == null) throw new ArgumentNullException(nameof(builder));
4040
builder.ConfigureServices(collection =>
41-
collection.AddSingleton<ILoggerFactory>(new SerilogLoggerFactory(logger, dispose)));
41+
collection.AddSingleton<ILoggerFactory>(services => new SerilogLoggerFactory(logger, dispose)));
4242
return builder;
4343
}
4444

4545
/// <summary>Sets Serilog as the logging provider.</summary>
46+
/// <remarks>
47+
/// A <see cref="WebHostBuilderContext"/> is supplied so that configuration and hosting information can be used.
48+
/// The logger will be shut down when application services are disposed.
49+
/// </remarks>
4650
/// <param name="builder">The web host builder to configure.</param>
47-
/// <param name="configureSerilog">The delegate for configuring the <see cref="LoggerConfiguration" /> that will be used to construct a <see cref="Logger" />.</param>
51+
/// <param name="configureLogger">The delegate for configuring the <see cref="LoggerConfiguration" /> that will be used to construct a <see cref="Logger" />.</param>
52+
/// <param name="preserveStaticLogger">Indicates whether to preserve the value of <see cref="Log.Logger"/>.</param>
4853
/// <returns>The web host builder.</returns>
49-
public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Action<WebHostBuilderContext, LoggerConfiguration> configureSerilog)
54+
public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Action<WebHostBuilderContext, LoggerConfiguration> configureLogger, bool preserveStaticLogger = false)
5055
{
5156
if (builder == null) throw new ArgumentNullException(nameof(builder));
52-
if (configureSerilog == null) throw new ArgumentNullException(nameof(configureSerilog));
53-
builder.ConfigureServices
54-
(
55-
(context, collection) =>
56-
{
57-
var loggerConfiguration = new LoggerConfiguration();
58-
configureSerilog(context, loggerConfiguration);
59-
collection.AddSingleton<ILoggerFactory>(new SerilogLoggerFactory(loggerConfiguration.CreateLogger(), true));
60-
}
61-
);
57+
if (configureLogger == null) throw new ArgumentNullException(nameof(configureLogger));
58+
builder.ConfigureServices((context, collection) =>
59+
{
60+
var loggerConfiguration = new LoggerConfiguration();
61+
configureLogger(context, loggerConfiguration);
62+
var logger = loggerConfiguration.CreateLogger();
63+
collection.AddSingleton<ILoggerFactory>(services => new SerilogLoggerFactory(logger, true));
64+
if (!preserveStaticLogger) Log.Logger = logger;
65+
});
6266
return builder;
6367
}
6468
}

0 commit comments

Comments
 (0)