Skip to content

Commit 55d9d67

Browse files
authored
Merge pull request #1 from GoldenCrystal/dev
Add an overload to UseSerilog() for inline initialization during program startup
2 parents 5e59109 + 79b7b1e commit 55d9d67

File tree

3 files changed

+74
-2
lines changed

3 files changed

+74
-2
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.

serilog-aspnetcore.sln

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

22
Microsoft Visual Studio Solution File, Format Version 12.00
33
# Visual Studio 15
4-
VisualStudioVersion = 15.0.26730.10
4+
VisualStudioVersion = 15.0.26730.12
55
MinimumVisualStudioVersion = 10.0.40219.1
66
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A1893BD1-333D-4DFE-A0F0-DDBB2FE526E0}"
77
EndProject

src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,40 @@ 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)));
42+
return builder;
43+
}
44+
45+
/// <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>
50+
/// <param name="builder">The web host builder to configure.</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>
53+
/// <returns>The web host builder.</returns>
54+
public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Action<WebHostBuilderContext, LoggerConfiguration> configureLogger, bool preserveStaticLogger = false)
55+
{
56+
if (builder == null) throw new ArgumentNullException(nameof(builder));
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+
if (preserveStaticLogger)
64+
{
65+
collection.AddSingleton<ILoggerFactory>(services => new SerilogLoggerFactory(logger, true));
66+
}
67+
else
68+
{
69+
// Passing a `null` logger to `SerilogLoggerFactory` results in disposal via
70+
// `Log.CloseAndFlush()`, which additionally replaces the static logger with a no-op.
71+
Log.Logger = logger;
72+
collection.AddSingleton<ILoggerFactory>(services => new SerilogLoggerFactory(null, true));
73+
}
74+
});
4275
return builder;
4376
}
4477
}

0 commit comments

Comments
 (0)