Skip to content

Commit 3fa0fcd

Browse files
committed
Added new extension method to configure serilog from services.
1 parent 07286fc commit 3fa0fcd

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
using System;
2+
using Microsoft.Extensions.Logging;
3+
using Serilog.Extensions.Logging;
4+
using System.ComponentModel;
5+
6+
namespace Serilog
7+
{
8+
/// <summary>
9+
/// Extends <see cref="IServiceCollection"/> with Serilog configuration methods.
10+
/// </summary>
11+
public static class SerilogLoggerServicesExtensions
12+
{
13+
/// <summary>
14+
/// Add Serilog to the logging pipeline.
15+
/// </summary>
16+
/// <param name="services">The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" /> to add services to.</param>
17+
/// <param name="logger">The Serilog logger; if not supplied, the static <see cref="Serilog.Log"/> will be used.</param>
18+
/// <returns>The logger factory.</returns>
19+
[EditorBrowsable(EditorBrowsableState.Never)]
20+
public static IServiceCollection AddSerilog(this IServiceCollection services, ILogger logger)
21+
{
22+
if (services == null) throw new ArgumentNullException(nameof(services));
23+
24+
return services.AddSerilog(logger, false);
25+
}
26+
27+
/// <summary>
28+
/// Add Serilog to the logging pipeline.
29+
/// </summary>
30+
/// <param name="services">The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" /> to add services to.</param>
31+
/// <param name="logger">The Serilog logger; if not supplied, the static <see cref="Serilog.Log"/> will be used.</param>
32+
/// <param name="dispose">When true, dispose <paramref name="logger"/> when the framework disposes the provider. If the
33+
/// logger is not specified but <paramref name="dispose"/> is true, the <see cref="Log.CloseAndFlush()"/> method will be
34+
/// called on the static <see cref="Log"/> class instead.</param>
35+
/// <returns>The logger factory.</returns>
36+
public static IServiceCollection AddSerilog(this IServiceCollection services, Serilog.ILogger logger = null, bool dispose = false)
37+
{
38+
if (services == null) throw new ArgumentNullException(nameof(services));
39+
40+
services.AddLogging(builder => builder.AddProvider(new SerilogLoggerProvider(logger, dispose)));
41+
42+
return services;
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)