Skip to content

Commit 6e59a36

Browse files
authored
Merge pull request #12 from serilog/dev
2.1.0 Release
2 parents e374103 + 843a569 commit 6e59a36

File tree

4 files changed

+67
-19
lines changed

4 files changed

+67
-19
lines changed

README.md

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Install-Package Serilog.AspNetCore -DependencyVersion Highest
1212
Install-Package Serilog.Sinks.Console
1313
```
1414

15-
**Next**, in your application's _Program.cs_ file, configure Serilog first:
15+
**Next**, in your application's _Program.cs_ file, configure Serilog first. A `try`/`catch` block will ensure any configuration issues are appropriately logged:
1616

1717
```csharp
1818
public class Program
@@ -25,25 +25,11 @@ public class Program
2525
.Enrich.FromLogContext()
2626
.WriteTo.Console()
2727
.CreateLogger();
28-
```
29-
30-
Then, add `UseSerilog()` to the web host builder. A `try`/`catch` block will ensure any configuration issues are appropriately logged:
3128

32-
```csharp
3329
try
3430
{
3531
Log.Information("Starting web host");
36-
37-
var host = new WebHostBuilder()
38-
.UseKestrel()
39-
.UseContentRoot(Directory.GetCurrentDirectory())
40-
.UseIISIntegration()
41-
.UseStartup<Startup>()
42-
.UseSerilog() // <-- Add this line
43-
.Build();
44-
45-
host.Run();
46-
32+
BuildWebHost(args).Run();
4733
return 0;
4834
}
4935
catch (Exception ex)
@@ -56,6 +42,16 @@ Then, add `UseSerilog()` to the web host builder. A `try`/`catch` block will ens
5642
Log.CloseAndFlush();
5743
}
5844
}
45+
```
46+
47+
Then, add `UseSerilog()` to the web host builder in `BuildWebHost()`.
48+
49+
```csharp
50+
public static IWebHost BuildWebHost(string[] args) =>
51+
WebHost.CreateDefaultBuilder(args)
52+
.UseStartup<Startup>()
53+
.UseSerilog() // <-- Add this line
54+
.Build();
5955
}
6056
```
6157

@@ -83,6 +79,25 @@ That's it! With the level bumped up a little you will see log output like:
8379

8480
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.
8581

82+
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).
83+
8684
### Using the package
8785

8886
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.
87+
88+
**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.
89+
90+
### Inline initialization
91+
92+
You can alternatively configure Serilog using a delegate as shown below:
93+
94+
```csharp
95+
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
96+
.ReadFrom.Configuration(hostingContext.Configuration)
97+
.Enrich.FromLogContext()
98+
.WriteTo.Console())
99+
```
100+
101+
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.
102+
103+
If this method is used, `Log.Logger` is assigned implicitly, and closed when the app is shut down.

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/Serilog.AspNetCore.csproj

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

33
<PropertyGroup>
44
<Description>Serilog support for ASP.NET Core logging</Description>
5-
<VersionPrefix>2.0.0</VersionPrefix>
5+
<VersionPrefix>2.1.0</VersionPrefix>
66
<Authors>Microsoft;Serilog Contributors</Authors>
77
<TargetFrameworks>netstandard2.0</TargetFrameworks>
88
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>

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)