-
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Imported Tingle.Extensions.Serilog (#157)
- Loading branch information
1 parent
d0d6b69
commit 686bd48
Showing
20 changed files
with
532 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"cSpell.words": [ | ||
"Serilog" | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
var host = Host.CreateDefaultBuilder(args) | ||
.UseSerilog(builder => | ||
{ | ||
builder.ConfigureSensitiveDataMasking(options => | ||
{ | ||
options.ExcludeProperties.Add("SomeNecessaryProperty"); | ||
}); | ||
}) | ||
.ConfigureServices(services => | ||
{ | ||
services.AddHostedService<Worker>(); | ||
}) | ||
.Build(); | ||
|
||
await host.RunAsync(); | ||
|
||
class Worker : BackgroundService | ||
{ | ||
private readonly ILogger logger; | ||
|
||
public Worker(ILogger<Worker> logger) | ||
{ | ||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); | ||
} | ||
|
||
protected override async Task ExecuteAsync(CancellationToken stoppingToken) | ||
{ | ||
while (!stoppingToken.IsCancellationRequested) | ||
{ | ||
logger.LogInformation("Worker running at: {time:R}", DateTimeOffset.Now); | ||
await Task.Delay(2000, stoppingToken); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
{ | ||
"profiles": { | ||
"SerilogSample": { | ||
"commandName": "Project", | ||
"dotnetRunMessages": true, | ||
"environmentVariables": { | ||
"DOTNET_ENVIRONMENT": "Development" | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Worker"> | ||
|
||
<PropertyGroup> | ||
<UserSecretsId>cfddbd80-2b06-4021-9fae-d2f1ecca48af</UserSecretsId> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\..\src\Tingle.Extensions.Serilog\Tingle.Extensions.Serilog.csproj" /> | ||
</ItemGroup> | ||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Information", | ||
"Microsoft.Hosting.Lifetime": "Information" | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Information", | ||
"Microsoft.Hosting.Lifetime": "Information" | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
using Microsoft.Extensions.Logging; | ||
using Serilog.Events; | ||
|
||
namespace Microsoft.Extensions.Configuration; | ||
|
||
internal static class ConfigurationExtensions | ||
{ | ||
public static LogEventLevel GetDefaultEventLevelForProvider(this IConfiguration configuration, string providerName) | ||
{ | ||
return Enum.TryParse<LogLevel>(configuration[$"Logging:{providerName}:LogLevel:Default"], ignoreCase: true, out var parsed) | ||
? parsed.ToLogEventLevel() | ||
: LogEventLevel.Verbose; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.Logging; | ||
using Serilog; | ||
using Serilog.Configuration; | ||
|
||
namespace Tingle.Extensions.Serilog; | ||
|
||
internal class ConvertedSerilogSettings : ILoggerSettings | ||
{ | ||
private readonly IConfiguration configuration; | ||
|
||
public ConvertedSerilogSettings(IConfiguration configuration) | ||
{ | ||
this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); | ||
} | ||
|
||
public void Configure(LoggerConfiguration loggerConfiguration) | ||
{ | ||
const string DefaultKey = "Default"; | ||
|
||
// configure provider-agnostic levels | ||
var children = configuration.GetSection("LogLevel").GetChildren(); | ||
foreach (var child in children) | ||
{ | ||
var source = child.Key; | ||
var level = Enum.Parse<LogLevel>(child.Value!).ToLogEventLevel(); | ||
if (string.Equals(source, DefaultKey, StringComparison.OrdinalIgnoreCase)) | ||
{ | ||
loggerConfiguration.MinimumLevel.Is(level); | ||
} | ||
else | ||
{ | ||
loggerConfiguration.MinimumLevel.Override(source, level); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
using Microsoft.Extensions.Hosting; | ||
using Serilog.Core; | ||
using Serilog.Events; | ||
using System.Reflection; | ||
|
||
namespace Tingle.Extensions.Serilog; | ||
|
||
internal class EnvironmentEnricher : ILogEventEnricher | ||
{ | ||
private readonly IHostEnvironment environment; | ||
|
||
private LogEventProperty? applicationName, applicationVersion; | ||
private LogEventProperty? environmentName, machineName; | ||
|
||
public EnvironmentEnricher(IHostEnvironment environment) | ||
{ | ||
this.environment = environment ?? throw new ArgumentNullException(nameof(environment)); | ||
} | ||
|
||
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) | ||
{ | ||
applicationName ??= propertyFactory.CreateProperty( | ||
name: "ApplicationName", | ||
value: environment.ApplicationName); | ||
|
||
applicationVersion ??= propertyFactory.CreateProperty( | ||
name: "ApplicationVersion", | ||
value: GetVersion()); | ||
|
||
environmentName ??= propertyFactory.CreateProperty( | ||
name: "EnvironmentName", | ||
value: environment.EnvironmentName); | ||
|
||
machineName ??= propertyFactory.CreateProperty( | ||
name: "MachineName", | ||
value: Environment.MachineName); | ||
|
||
logEvent.AddPropertyIfAbsent(applicationName); | ||
logEvent.AddPropertyIfAbsent(applicationVersion); | ||
logEvent.AddPropertyIfAbsent(environmentName); | ||
logEvent.AddPropertyIfAbsent(machineName); | ||
} | ||
|
||
private static string GetVersion() | ||
{ | ||
var assembly = Assembly.GetEntryAssembly()!; | ||
var attr = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>(); | ||
return attr != null && !string.IsNullOrWhiteSpace(attr.InformationalVersion) | ||
? attr.InformationalVersion | ||
: assembly.GetName().Version!.ToString(3); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Logging; | ||
|
||
namespace Microsoft.Extensions.Hosting; | ||
|
||
/// <summary>Extension methods for <see cref="IHostBuilder"/>.</summary> | ||
public static class IHostBuilderExtensions | ||
{ | ||
/// <summary> | ||
/// Add Serilog services via <see cref="SerilogBuilder"/>. | ||
/// This replaces the default <see cref="ILoggerProvider"/>. | ||
/// </summary> | ||
/// <param name="builder">The <see cref="IHostBuilder"/> builder to configure.</param> | ||
/// <param name="setupAction">An optional action for setting up Serilog.</param> | ||
/// <remarks> | ||
/// By default, this sets up destructuring of simple exceptions, sensitive data masking, reading of log levels | ||
/// from the <c>Logging:</c> configuration section, writing to console, debug and SEQ. | ||
/// For more specifics you can inspect <see cref="SerilogBuilder"/>. | ||
/// The logger will be shut down when application services are disposed. | ||
/// <br/> | ||
/// <br/> | ||
/// A <see cref="HostBuilderContext"/> is supplied so that configuration and hosting information can be used. | ||
/// </remarks> | ||
public static IHostBuilder UseSerilog(this IHostBuilder builder, Action<SerilogBuilder> setupAction) | ||
=> builder.UseSerilog((_, builder) => setupAction?.Invoke(builder)); | ||
|
||
/// <summary> | ||
/// Add Serilog services via <see cref="SerilogBuilder"/>. | ||
/// This replaces the default <see cref="ILoggerProvider"/>. | ||
/// </summary> | ||
/// <param name="builder">The <see cref="IHostBuilder"/> builder to configure.</param> | ||
/// <param name="setupAction">An optional action for setting up Serilog.</param> | ||
/// <remarks> | ||
/// By default, this sets up destructuring of simple exceptions, sensitive data masking, reading of log levels | ||
/// from the <c>Logging:</c> configuration section, writing to console, debug and SEQ. | ||
/// For more specifics you can inspect <see cref="SerilogBuilder"/>. | ||
/// The logger will be shut down when application services are disposed. | ||
/// <br/> | ||
/// <br/> | ||
/// A <see cref="HostBuilderContext"/> is supplied so that configuration and hosting information can be used. | ||
/// </remarks> | ||
public static IHostBuilder UseSerilog(this IHostBuilder builder, Action<HostBuilderContext, SerilogBuilder>? setupAction = null) | ||
{ | ||
ArgumentNullException.ThrowIfNull(builder); | ||
|
||
return builder.ConfigureServices((context, services) => services.AddSerilog(builder => setupAction?.Invoke(context, builder))); | ||
} | ||
} |
49 changes: 49 additions & 0 deletions
49
src/Tingle.Extensions.Serilog/IServiceCollectionExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
using Microsoft.Extensions.Logging; | ||
|
||
namespace Microsoft.Extensions.DependencyInjection; | ||
|
||
/// <summary>Extension methods for <see cref="IServiceCollection"/>.</summary> | ||
public static class IServiceCollectionExtensions | ||
{ | ||
/// <summary> | ||
/// Add Serilog services via <see cref="SerilogBuilder"/>. | ||
/// This replaces the default <see cref="ILoggerProvider"/>. | ||
/// </summary> | ||
/// <param name="services">The <see cref="IServiceCollection"/> instance to add services to.</param> | ||
/// <returns>An <see cref="SerilogBuilder"/> to continue setting up Serilog.</returns> | ||
/// <remarks> | ||
/// By default, this sets up destructuring of simple exceptions, sensitive data masking, reading of log levels | ||
/// from the <c>Logging:</c> configuration section, writing to console, debug and SEQ. | ||
/// For more specifics you can inspect <see cref="SerilogBuilder"/>. | ||
/// The logger will be shut down when application services are disposed. | ||
/// </remarks> | ||
public static SerilogBuilder AddSerilog(this IServiceCollection services) | ||
{ | ||
ArgumentNullException.ThrowIfNull(services); | ||
return new SerilogBuilder(services); | ||
} | ||
|
||
/// <summary> | ||
/// Add Serilog services via <see cref="SerilogBuilder"/>. | ||
/// This replaces the default <see cref="ILoggerProvider"/>. | ||
/// </summary> | ||
/// <param name="services">The <see cref="IServiceCollection"/> instance to add services to.</param> | ||
/// <param name="setupAction">An optional action for setting up Serilog.</param> | ||
/// <returns></returns> | ||
/// <remarks> | ||
/// By default, this sets up destructuring of simple exceptions, sensitive data masking, reading of log levels | ||
/// from the <c>Logging:</c> configuration section, writing to console, debug and SEQ. | ||
/// For more specifics you can inspect <see cref="SerilogBuilder"/>. | ||
/// The logger will be shut down when application services are disposed. | ||
/// </remarks> | ||
public static IServiceCollection AddSerilog(this IServiceCollection services, Action<SerilogBuilder>? setupAction = null) | ||
{ | ||
ArgumentNullException.ThrowIfNull(services); | ||
|
||
var builder = services.AddSerilog(); | ||
|
||
setupAction?.Invoke(builder); | ||
|
||
return services; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
using Serilog.Events; | ||
|
||
namespace Microsoft.Extensions.Logging; | ||
|
||
internal static class LoggingExtensions | ||
{ | ||
public static LogEventLevel ToLogEventLevel(this LogLevel level) | ||
{ | ||
// https://github.com/serilog/serilog-extensions-logging/blob/e25ed7ddfd0c664bd3a7e9cdbeeec6f87ff12964/src/Serilog.Extensions.Logging/Extensions/Logging/LevelConvert.cs#L35-L54 | ||
return level switch | ||
{ | ||
LogLevel.Trace => LogEventLevel.Verbose, | ||
LogLevel.Debug => LogEventLevel.Debug, | ||
LogLevel.Information => LogEventLevel.Information, | ||
LogLevel.Warning => LogEventLevel.Warning, | ||
LogLevel.Error => LogEventLevel.Error, | ||
LogLevel.Critical => LogEventLevel.Fatal, | ||
LogLevel.None => LogEventLevel.Fatal, | ||
_ => LogEventLevel.Verbose, | ||
}; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
# Tingle.Extensions.Serilog | ||
|
||
This library provides convenience extensions and logic for registering Serilog in applications with support for various hosts while setting up basic thins to match the default logging setup in the framework. | ||
|
||
This includes: | ||
|
||
- Destructuring is enabled/added by default | ||
- Sensitive data masking is enabled/added by default. | ||
- Console and Debug are registered by default. | ||
- Enrichment of the current environment based on `IHostEnvironment` | ||
- Conversion of log levels hence you can continue to use the `Logging` section. | ||
- [SEQ](https://datalust.co/seq) is added by default when `Logging:Seq:ServerUrl` or `Seq:ServerUrl` configuration is available. (Use `Logging:Seq:ApiKey` or `Seq:ApiKey` to set the key). | ||
- Registration via `IServiceCollection` and `IHostBuilder` (with the defaults above) | ||
|
||
Consult the [sample](https://github.com/tinglesoftware/dotnet-extensions/tree/main/samples/SerilogSample) or the [builder](https://github.com/tinglesoftware/dotnet-extensions/blob/main/src/Tingle.Extensions.Serilog/SerilogBuilder.cs) for more on how to use or what happens underneath. |
Oops, something went wrong.