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

Add an overload to UseSerilog() for inline initialization during program startup #1

Merged
merged 3 commits into from
Oct 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,42 @@ Tip: to see Serilog output in the Visual Studio output window when running under
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.

### Alternative configuration

You can chose to build the logger as part of the `WebHostBuilder` pipeline, and thus benefit from the application configuration.
The following code shows an example of such a configuration:

````csharp
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
// Load the application configuration over the web host configuration.
.ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
{
configurationBuilder
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
})
// Configure Serilog to be used as the logger for the whole application.
.UseSerilog((hostingContext, loggerConfiguration) =>
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
.WriteTo.Console()
)
.UseIISIntegration()
.UseStartup<Startup>()
.Build();

host.Run();
}
}
````

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