Skip to content

Commit

Permalink
Update format
Browse files Browse the repository at this point in the history
  • Loading branch information
jianmingyong committed Jan 2, 2024
1 parent 8cb431e commit 7548e34
Show file tree
Hide file tree
Showing 24 changed files with 381 additions and 354 deletions.
2 changes: 1 addition & 1 deletion TheDialgaTeam.Serilog/Configuration/LogLevelOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

namespace TheDialgaTeam.Serilog.Configuration;

internal sealed class LogLevelOptions
public sealed class LogLevelOptions
{
public LogLevel Default { get; set; } = LogLevel.Information;

Expand Down
39 changes: 30 additions & 9 deletions TheDialgaTeam.Serilog/Configuration/SerilogLoggerSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,26 +24,47 @@
using Serilog;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Events;
using Serilog.Extensions.Logging;

namespace TheDialgaTeam.Serilog.Configuration;

internal sealed class SerilogLoggerSettings(IOptionsMonitor<LogLevelOptions> logLevelOptionsMonitor) : ILoggerSettings
internal sealed class SerilogLoggerSettings(IOptionsMonitor<LogLevelOptions> logLevelOptionsMonitor) : ILoggerSettings, IDisposable
{
private readonly LoggingLevelSwitch _defaultLoggingLevelSwitch = new();
private readonly Dictionary<string, LoggingLevelSwitch> _overridesLoggingLevelSwitch = new();

private IDisposable? _disposable;

public void Configure(LoggerConfiguration loggerConfiguration)
{
loggerConfiguration.Filter.ByIncludingOnly(logEvent =>
UpdateLogLevel(logLevelOptionsMonitor.CurrentValue);
loggerConfiguration.MinimumLevel.ControlledBy(_defaultLoggingLevelSwitch);

foreach (var (sourceContext, logLevel) in logLevelOptionsMonitor.CurrentValue.Overrides)
{
string? sourceContext = null;
var temp = new LoggingLevelSwitch(LevelConvert.ToSerilogLevel(logLevel));
_overridesLoggingLevelSwitch.Add(sourceContext, temp);
loggerConfiguration.MinimumLevel.Override(sourceContext, temp);
}

_disposable = logLevelOptionsMonitor.OnChange(UpdateLogLevel);
}

private void UpdateLogLevel(LogLevelOptions options)
{
_defaultLoggingLevelSwitch.MinimumLevel = LevelConvert.ToSerilogLevel(options.Default);

if (logEvent.Properties.TryGetValue(Constants.SourceContextPropertyName, out var logEventPropertyValue) &&
logEventPropertyValue is ScalarValue { Value: string sourceContextValue })
foreach (var (sourceContext, logLevel) in options.Overrides)
{
if (_overridesLoggingLevelSwitch.TryGetValue(sourceContext, out var levelSwitch))
{
sourceContext = sourceContextValue;
levelSwitch.MinimumLevel = LevelConvert.ToSerilogLevel(logLevel);
}
}
}

return LevelConvert.ToExtensionsLevel(logEvent.Level) >= logLevelOptionsMonitor.CurrentValue.GetMinimumLogLevel(sourceContext);
});
public void Dispose()
{
_disposable?.Dispose();
}
}
19 changes: 13 additions & 6 deletions TheDialgaTeam.Serilog/Extensions/HostBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,6 @@
using Microsoft.Extensions.Hosting;
using Serilog;
using TheDialgaTeam.Serilog.Configuration;
using TheDialgaTeam.Serilog.Formatting;
using TheDialgaTeam.Serilog.Formatting.Options;
using TheDialgaTeam.Serilog.Sinks.Action;

namespace TheDialgaTeam.Serilog.Extensions;

Expand All @@ -38,9 +35,19 @@ public static IHostBuilder ConfigureSerilog(this IHostBuilder hostBuilder, Actio
return hostBuilder.ConfigureServices(static collection =>
{
collection.AddOptions<LogLevelOptions>().BindConfiguration("TheDialgaTeam.Serilog:LogLevel");
collection.AddOptions<LogLevelMessageTemplateOptions>().BindConfiguration("TheDialgaTeam.Serilog:LogLevelMessageTemplate");
collection.TryAddSingleton<AnsiMessageTemplateTextFormatterOptions>();
collection.TryAddSingleton<ActionSinkOptions>();
collection.TryAddSingleton<SerilogLoggerSettings>();
}).UseSerilog((context, provider, configuration) =>
{
configuration.ReadFrom.Settings(provider.GetRequiredService<SerilogLoggerSettings>());
configureLogger(context, provider, configuration);
});
}

public static IHostBuilder ConfigureSerilog(this IHostBuilder hostBuilder, string logLevelConfigSection, Action<HostBuilderContext, IServiceProvider, LoggerConfiguration> configureLogger)
{
return hostBuilder.ConfigureServices(collection =>
{
collection.AddOptions<LogLevelOptions>().BindConfiguration(logLevelConfigSection);
collection.TryAddSingleton<SerilogLoggerSettings>();
}).UseSerilog((context, provider, configuration) =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
namespace TheDialgaTeam.Serilog.Formatting;

public sealed class AnsiMessageTemplateTextFormatter(
AnsiMessageTemplateTextFormatterOptions options,
LogLevelMessageTemplateOptions options,
IFormatProvider? formatProvider = null) : ITextFormatter
{
private readonly AnsiTemplateTextParser _ansiTemplateTextParser = new();
Expand All @@ -42,10 +42,8 @@ public void Format(LogEvent logEvent, TextWriter output)
{
sourceContext = sourceContextValue;
}

var logLevelMessageTemplateOptions = options.LogLevelMessageTemplateOptions;

var messageTemplate = logLevelMessageTemplateOptions.GetMessageTemplate(sourceContext, LevelConvert.ToExtensionsLevel(logEvent.Level));

var messageTemplate = options.GetMessageTemplate(sourceContext, LevelConvert.ToExtensionsLevel(logEvent.Level));

foreach (var messageTemplateToken in _ansiTemplateTextParser.GetMessageTemplateTokens(messageTemplate))
{
Expand Down

This file was deleted.

196 changes: 196 additions & 0 deletions TheDialgaTeam.Serilog/Formatting/LogLevelMessageTemplateOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
// MIT License
//
// Copyright (c) 2023 Yong Jian Ming
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using Microsoft.Extensions.Logging;

namespace TheDialgaTeam.Serilog.Formatting;

public sealed class LogLevelMessageTemplateOptions
{
public LogLevelMessageTemplate Default { get; set; } = new();

public Dictionary<string, LogLevelMessageTemplate> Overrides { get; set; } = new();

public string GetMessageTemplate(string? sourceContext, LogLevel logLevel)
{
var messageTemplate = GetLogLevelMessageTemplate(sourceContext);

return logLevel switch
{
LogLevel.Trace => messageTemplate.Trace ?? messageTemplate.Default,
LogLevel.Debug => messageTemplate.Debug ?? messageTemplate.Default,
LogLevel.Information => messageTemplate.Information ?? messageTemplate.Default,
LogLevel.Warning => messageTemplate.Warning ?? messageTemplate.Default,
LogLevel.Error => messageTemplate.Error ?? messageTemplate.Default,
LogLevel.Critical => messageTemplate.Critical ?? messageTemplate.Default,
var _ => string.Empty
};
}

private LogLevelMessageTemplate GetLogLevelMessageTemplate(string? sourceContext)
{
if (sourceContext is null)
{
return Default;
}

foreach (var (key, value) in Overrides.OrderByDescending(pair => pair.Key))
{
if (sourceContext.StartsWith(key) && (sourceContext.Length == key.Length || sourceContext[key.Length] == '.'))
{
return value;
}
}

return Default;
}
}

public sealed class LogLevelMessageTemplateOptionsBuilder
{
private readonly LogLevelMessageTemplateOptions _options = new();

public LogLevelMessageTemplateOptionsBuilder SetDefault(LogLevelMessageTemplate messageTemplate)
{
_options.Default = messageTemplate;
return this;
}

public LogLevelMessageTemplateOptionsBuilder SetDefault(Action<LogLevelMessageTemplateBuilder> messageTemplate)
{
var logLevelMessageTemplateBuilder = new LogLevelMessageTemplateBuilder();
messageTemplate(logLevelMessageTemplateBuilder);
_options.Default = logLevelMessageTemplateBuilder.Build();
return this;
}

public LogLevelMessageTemplateOptionsBuilder SetOverrides(Dictionary<string, LogLevelMessageTemplate> overrides)
{
_options.Overrides = overrides;
return this;
}

public LogLevelMessageTemplateOptionsBuilder SetOverrides(string context, LogLevelMessageTemplate messageTemplate)
{
if (!_options.Overrides.TryAdd(context, messageTemplate))
{
_options.Overrides[context] = messageTemplate;
}

return this;
}

public LogLevelMessageTemplateOptionsBuilder SetOverrides(string context, Action<LogLevelMessageTemplateBuilder> messageTemplate)
{
var logLevelMessageTemplateBuilder = new LogLevelMessageTemplateBuilder();
messageTemplate(logLevelMessageTemplateBuilder);

var logLevelMessageTemplate = logLevelMessageTemplateBuilder.Build();

if (!_options.Overrides.TryAdd(context, logLevelMessageTemplate))
{
_options.Overrides[context] = logLevelMessageTemplate;
}

return this;
}

public LogLevelMessageTemplateOptionsBuilder ClearOverrides()
{
_options.Overrides.Clear();
return this;
}

public LogLevelMessageTemplateOptions Build()
{
return _options;
}
}

public sealed class LogLevelMessageTemplate
{
public string Default { get; set; } = "{Timestamp:yyyy-MM-dd HH:mm:ss} {Message:l}{NewLine}{Exception}";

public string? Trace { get; set; }

public string? Debug { get; set; }

public string? Information { get; set; }

public string? Warning { get; set; }

public string? Error { get; set; }

public string? Critical { get; set; }
}

public sealed class LogLevelMessageTemplateBuilder
{
private readonly LogLevelMessageTemplate _template = new();

public LogLevelMessageTemplateBuilder SetDefault(string template)
{
_template.Default = template;
return this;
}

public LogLevelMessageTemplateBuilder SetTrace(string? template)
{
_template.Trace = template;
return this;
}

public LogLevelMessageTemplateBuilder SetDebug(string? template)
{
_template.Trace = template;
return this;
}

public LogLevelMessageTemplateBuilder SetInformation(string? template)
{
_template.Trace = template;
return this;
}

public LogLevelMessageTemplateBuilder SetWarning(string? template)
{
_template.Warning = template;
return this;
}

public LogLevelMessageTemplateBuilder SetError(string? template)
{
_template.Error = template;
return this;
}

public LogLevelMessageTemplateBuilder SetCritical(string? template)
{
_template.Critical = template;
return this;
}

public LogLevelMessageTemplate Build()
{
return _template;
}
}
Loading

0 comments on commit 7548e34

Please sign in to comment.