Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2.1.0 Release #12

Merged
merged 9 commits into from
Oct 22, 2017
47 changes: 31 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<Startup>()
.UseSerilog() // <-- Add this line
.Build();

host.Run();

BuildWebHost(args).Run();
return 0;
}
catch (Exception ex)
Expand All @@ -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<Startup>()
.UseSerilog() // <-- Add this line
.Build();
}
```

Expand Down Expand Up @@ -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.
2 changes: 1 addition & 1 deletion serilog-aspnetcore.sln
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/Serilog.AspNetCore/Serilog.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<Description>Serilog support for ASP.NET Core logging</Description>
<VersionPrefix>2.0.0</VersionPrefix>
<VersionPrefix>2.1.0</VersionPrefix>
<Authors>Microsoft;Serilog Contributors</Authors>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
Expand Down
35 changes: 34 additions & 1 deletion src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ILoggerFactory>(new SerilogLoggerFactory(logger, dispose)));
collection.AddSingleton<ILoggerFactory>(services => new SerilogLoggerFactory(logger, dispose)));
return builder;
}

/// <summary>Sets Serilog as the logging provider.</summary>
/// <remarks>
/// A <see cref="WebHostBuilderContext"/> is supplied so that configuration and hosting information can be used.
/// The logger will be shut down when application services are disposed.
/// </remarks>
/// <param name="builder">The web host builder to configure.</param>
/// <param name="configureLogger">The delegate for configuring the <see cref="LoggerConfiguration" /> that will be used to construct a <see cref="Logger" />.</param>
/// <param name="preserveStaticLogger">Indicates whether to preserve the value of <see cref="Log.Logger"/>.</param>
/// <returns>The web host builder.</returns>
public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Action<WebHostBuilderContext, LoggerConfiguration> 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<ILoggerFactory>(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<ILoggerFactory>(services => new SerilogLoggerFactory(null, true));
}
});
return builder;
}
}
Expand Down