Skip to content

Commit

Permalink
fix(app): enable serilog
Browse files Browse the repository at this point in the history
  • Loading branch information
SonicGD committed Oct 14, 2023
1 parent fbd7bc3 commit 82f9286
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 77 deletions.
9 changes: 7 additions & 2 deletions src/Sitko.Core.App/HostedLifecycleService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,27 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Sitko.Core.App.Logging;

namespace Sitko.Core.App;

public class HostedLifecycleService : IHostedLifecycleService
internal class HostedLifecycleService : IHostedLifecycleService
{
private readonly ILogger<HostedLifecycleService> logger;
private readonly IApplicationContext applicationContext;
private readonly IServiceProvider serviceProvider;
private readonly SerilogConfigurator serilogConfigurator;

private readonly IReadOnlyList<ApplicationModuleRegistration> enabledModules;

public HostedLifecycleService(ILogger<HostedLifecycleService> logger, IApplicationContext applicationContext,
IServiceProvider serviceProvider, IEnumerable<ApplicationModuleRegistration> applicationModuleRegistrations)
IServiceProvider serviceProvider, IEnumerable<ApplicationModuleRegistration> applicationModuleRegistrations,
SerilogConfigurator serilogConfigurator)
{
this.logger = logger;
this.applicationContext = applicationContext;
this.serviceProvider = serviceProvider;
this.serilogConfigurator = serilogConfigurator;
enabledModules =
ModulesHelper.GetEnabledModuleRegistrations(applicationContext, applicationModuleRegistrations);
}
Expand All @@ -30,6 +34,7 @@ public HostedLifecycleService(ILogger<HostedLifecycleService> logger, IApplicati
public async Task StartingAsync(CancellationToken cancellationToken)
{
await using var scope = serviceProvider.CreateAsyncScope();
serilogConfigurator.ApplyLogging(applicationContext, enabledModules);
foreach (var enabledModule in enabledModules)
{
var shouldContinue = await enabledModule.GetInstance()
Expand Down
23 changes: 0 additions & 23 deletions src/Sitko.Core.App/Logging/LoggingExtensions.cs

This file was deleted.

57 changes: 57 additions & 0 deletions src/Sitko.Core.App/Logging/SerilogConfigurator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using Serilog;
using Serilog.Events;

namespace Sitko.Core.App.Logging;

internal class SerilogConfigurator
{
private LoggerConfiguration loggerConfiguration = new();

private readonly List<Func<IApplicationContext, LoggerConfiguration, LoggerConfiguration>>
loggerConfigurationActions = new();

private readonly Dictionary<string, LogEventLevel> logEventLevels = new();

public SerilogConfigurator Configure(Func<LoggerConfiguration, LoggerConfiguration> configure)
{
loggerConfiguration = configure(loggerConfiguration);
return this;
}

private void RecreateLogger() => Log.Logger = loggerConfiguration.CreateLogger();

public SerilogConfigurator ConfigureLogLevel(string source, LogEventLevel level)
{
logEventLevels.Add(source, level);
return this;
}

public SerilogConfigurator ConfigureLogging(
Func<IApplicationContext, LoggerConfiguration, LoggerConfiguration> configure)
{
loggerConfigurationActions.Add(configure);
return this;
}

public void ApplyLogging(IApplicationContext applicationContext,
IEnumerable<ApplicationModuleRegistration> enabledModules)
{
foreach (var (key, value) in logEventLevels)
{
loggerConfiguration = loggerConfiguration.MinimumLevel.Override(key, value);
}

foreach (var moduleRegistration in ModulesHelper.GetEnabledModuleRegistrations<ILoggingModule>(
applicationContext, enabledModules))
{
loggerConfiguration = moduleRegistration.ConfigureLogging(applicationContext, loggerConfiguration);
}

foreach (var loggerConfigurationAction in loggerConfigurationActions)
{
loggerConfiguration = loggerConfigurationAction(applicationContext, loggerConfiguration);
}

RecreateLogger();
}
}
92 changes: 40 additions & 52 deletions src/Sitko.Core.App/SitkoCoreApplicationBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,76 +22,64 @@ public class SitkoCoreApplicationBuilder
private readonly List<ApplicationModuleRegistration> moduleRegistrations =
new();

private readonly SerilogConfigurator serilogConfigurator = new();

public SitkoCoreApplicationBuilder(IHostApplicationBuilder builder, string[] args)
{
this.Builder = builder;
Builder = builder;
var bootConfig = builder.Configuration.Build();
var argsProvider = new ApplicationArgsProvider(args);
BootApplicationContext = new BuilderApplicationContext(bootConfig, builder.Environment, argsProvider);

// configure logging
builder.Configuration.Add(new SerilogDynamicConfigurationSource());
var tmpLoggerConfiguration = new LoggerConfiguration();
tmpLoggerConfiguration = ConfigureDefautLogger(tmpLoggerConfiguration);
if (BootApplicationContext.Options.EnableConsoleLogging != true)
{
tmpLoggerConfiguration = tmpLoggerConfiguration.WriteTo.Console(
outputTemplate: ApplicationOptions.BaseConsoleLogFormat,
formatProvider: CultureInfo.InvariantCulture,
restrictedToMinimumLevel: LogEventLevel.Debug);
}

var tmpLogger = tmpLoggerConfiguration.CreateLogger();
Log.Logger = tmpLogger; // set default logger until host is started
Console.OutputEncoding = Encoding.UTF8;
InternalLogger = new SerilogLoggerFactory(tmpLogger)
.CreateLogger<SitkoCoreApplicationBuilder>();
AddModule<CommandsModule>();
builder.Logging.ClearProviders();
builder.Logging.AddSerilog();

serilogConfigurator.Configure(configuration => ConfigureDefautLogger(configuration));


builder.Services.AddSingleton<IApplicationArgsProvider>(argsProvider);
builder.Services.AddSingleton(serilogConfigurator);
builder.Services.AddSingleton<IApplicationContext, BuilderApplicationContext>();
builder.Services.AddTransient<IScheduler, Scheduler>();
builder.Services.AddFluentValidationExtensions();
builder.Services.AddTransient(typeof(ILocalizationProvider<>), typeof(LocalizationProvider<>));
builder.Services.AddHostedService<HostedLifecycleService>(); // только Hosted? Проверить для Wasm

Console.OutputEncoding = Encoding.UTF8;
var loggerConfiguration = new LoggerConfiguration();
loggerConfiguration
.WriteTo.Console(outputTemplate: ApplicationOptions.BaseConsoleLogFormat,
formatProvider: CultureInfo.InvariantCulture,
restrictedToMinimumLevel: LogEventLevel.Debug);
InternalLogger = new SerilogLoggerFactory(loggerConfiguration.CreateLogger())
.CreateLogger<SitkoCoreApplicationBuilder>();
AddModule<CommandsModule>();
}

protected ILogger<SitkoCoreApplicationBuilder> InternalLogger { get; }

protected Dictionary<string, LogEventLevel> LogEventLevels { get; } = new();

protected List<Func<IApplicationContext, LoggerConfiguration, LoggerConfiguration>>
LoggerConfigurationActions { get; } = new();

// TODO: WHEN?
private void ConfigureLogging()
{
LogInternal("Configure logging");
LoggingExtensions.ConfigureSerilog(BootApplicationContext, Builder.Logging,
configuration =>
{
configuration = configuration.Enrich.WithMachineName();
if (BootApplicationContext.Options.EnableConsoleLogging == true)
{
configuration = configuration.WriteTo.Console(
outputTemplate: BootApplicationContext.Options.ConsoleLogFormat,
formatProvider: CultureInfo.InvariantCulture);
}

return ConfigureLogging(BootApplicationContext, configuration);
});
}

protected virtual LoggerConfiguration ConfigureLogging(IApplicationContext applicationContext,
LoggerConfiguration loggerConfiguration)
protected LoggerConfiguration ConfigureDefautLogger(LoggerConfiguration loggerConfiguration)
{
foreach (var (key, value) in LogEventLevels)
{
loggerConfiguration = loggerConfiguration.MinimumLevel.Override(key, value);
}

foreach (var moduleRegistration in ModulesHelper.GetEnabledModuleRegistrations<ILoggingModule>(
applicationContext, moduleRegistrations))
{
loggerConfiguration = moduleRegistration.ConfigureLogging(applicationContext, loggerConfiguration);
}

foreach (var loggerConfigurationAction in LoggerConfigurationActions)
loggerConfiguration = loggerConfiguration.ReadFrom.Configuration(BootApplicationContext.Configuration);
loggerConfiguration = loggerConfiguration
.Enrich.FromLogContext()
.Enrich.WithProperty("App", BootApplicationContext.Name)
.Enrich.WithProperty("AppVersion", BootApplicationContext.Version)
.Enrich.WithProperty("AppEnvironment", BootApplicationContext.Environment)
.Enrich.WithMachineName();
if (BootApplicationContext.Options.EnableConsoleLogging == true)
{
loggerConfiguration = loggerConfigurationAction(applicationContext, loggerConfiguration);
loggerConfiguration = loggerConfiguration.WriteTo.Console(
outputTemplate: BootApplicationContext.Options.ConsoleLogFormat,
formatProvider: CultureInfo.InvariantCulture);
}

return loggerConfiguration;
Expand Down Expand Up @@ -176,14 +164,14 @@ protected virtual void ConfigureHostBuilder<TModule, TModuleOptions>(Application

public SitkoCoreApplicationBuilder ConfigureLogLevel(string source, LogEventLevel level)
{
LogEventLevels.Add(source, level);
serilogConfigurator.ConfigureLogLevel(source, level);
return this;
}

public SitkoCoreApplicationBuilder ConfigureLogging(
Func<IApplicationContext, LoggerConfiguration, LoggerConfiguration> configure)
{
LoggerConfigurationActions.Add(configure);
serilogConfigurator.ConfigureLogging(configure);
return this;
}

Expand Down

0 comments on commit 82f9286

Please sign in to comment.