Skip to content

Commit cba9446

Browse files
asvishnyakovOlegoO
andauthored
Refactor serilog initialization and add module initialization logging (#2871)
Co-authored-by: Oleg Zhuk <[email protected]>
1 parent d54129d commit cba9446

File tree

8 files changed

+42
-41
lines changed

8 files changed

+42
-41
lines changed

src/VirtoCommerce.Platform.Core/Logger/ConsoleLog.cs

+1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace VirtoCommerce.Platform.Core.Logger
44
{
5+
[Obsolete("Use Serilog's static Log.Logger or inject ILogger instead", DiagnosticId = "VC0010", UrlFormat = "https://docs.virtocommerce.org/platform/user-guide/versions/virto3-products-versions/")]
56
public static class ConsoleLog
67
{
78
public static void BeginOperation(string message)

src/VirtoCommerce.Platform.Modules/ModuleInitializer.cs

+4-2
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public ModuleInitializer(
4848
/// <summary>
4949
/// Initializes the specified module.
5050
/// </summary>
51-
/// <param name="moduleInfo">The module to initialize</param>
51+
/// <param name="moduleInfo">The module to initialize</param>
5252
public void Initialize(ModuleInfo moduleInfo)
5353
{
5454
if (moduleInfo == null)
@@ -80,6 +80,7 @@ public void Initialize(ModuleInfo moduleInfo)
8080
hasModuleCatalog.ModuleCatalog = _moduleCatalog;
8181
}
8282

83+
_loggerFacade.LogDebug("Initializing module {ModuleName}.", moduleInfo.ModuleName);
8384
moduleInstance.Initialize(_serviceCollection);
8485
moduleInfo.State = ModuleState.Initialized;
8586
}
@@ -103,6 +104,7 @@ public void PostInitialize(ModuleInfo moduleInfo, IApplicationBuilder appBuilder
103104
{
104105
if (moduleInstance != null)
105106
{
107+
_loggerFacade.LogDebug("Post-initializing module {ModuleName}.", moduleInfo.ModuleName);
106108
moduleInstance.PostInitialize(appBuilder);
107109
}
108110
}
@@ -115,7 +117,7 @@ public void PostInitialize(ModuleInfo moduleInfo, IApplicationBuilder appBuilder
115117
/// <summary>
116118
/// Handles any exception occurred in the module Initialization process,
117119
/// logs the error using the <see cref="ILogger"/> and throws a <see cref="ModuleInitializeException"/>.
118-
/// This method can be overridden to provide a different behavior.
120+
/// This method can be overridden to provide a different behavior.
119121
/// </summary>
120122
/// <param name="moduleInfo">The module metadata where the error happened.</param>
121123
/// <param name="exception">The exception thrown that is the cause of the current error.</param>

src/VirtoCommerce.Platform.Modules/ModuleManager.cs

+8-13
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,13 @@
33
using System.Linq;
44
using Microsoft.AspNetCore.Builder;
55
using Microsoft.Extensions.Logging;
6-
using VirtoCommerce.Platform.Core.Logger;
76
using VirtoCommerce.Platform.Core.Modularity;
87
using VirtoCommerce.Platform.Core.Modularity.Exceptions;
98

109
namespace VirtoCommerce.Platform.Modules
1110
{
1211
/// <summary>
13-
/// Component responsible for coordinating the modules' type loading and module initialization process.
12+
/// Component responsible for coordinating the modules' type loading and module initialization process.
1413
/// </summary>
1514
public class ModuleManager : IModuleManager, IDisposable
1615
{
@@ -77,17 +76,13 @@ private void RaiseLoadModuleCompleted(LoadModuleCompletedEventArgs e)
7776
/// </summary>
7877
public void Run()
7978
{
80-
ConsoleLog.BeginOperation("Initializing module catalog");
79+
_loggerFacade.LogInformation("Initializing module catalog");
8180

8281
this.ModuleCatalog.Initialize();
8382

84-
ConsoleLog.EndOperation();
85-
86-
ConsoleLog.BeginOperation("Loading modules");
83+
_loggerFacade.LogInformation("Loading modules");
8784

8885
this.LoadModulesWhenAvailable();
89-
90-
ConsoleLog.EndOperation();
9186
}
9287

9388

@@ -117,8 +112,8 @@ public void PostInitializeModule(ModuleInfo moduleInfo, IApplicationBuilder appl
117112
}
118113

119114
/// <summary>
120-
/// Returns the list of registered <see cref="IModuleTypeLoader"/> instances that will be
121-
/// used to load the types of modules.
115+
/// Returns the list of registered <see cref="IModuleTypeLoader"/> instances that will be
116+
/// used to load the types of modules.
122117
/// </summary>
123118
/// <value>The module type loaders.</value>
124119
public virtual IEnumerable<IModuleTypeLoader> ModuleTypeLoaders
@@ -161,8 +156,8 @@ protected virtual bool ModuleNeedsRetrieval(ModuleInfo moduleInfo)
161156

162157
if (moduleInfo.State == ModuleState.NotStarted)
163158
{
164-
// If we can instantiate the type, that means the module's assembly is already loaded into
165-
// the AppDomain and we don't need to retrieve it.
159+
// If we can instantiate the type, that means the module's assembly is already loaded into
160+
// the AppDomain and we don't need to retrieve it.
166161
bool isAvailable = Type.GetType(moduleInfo.ModuleType) != null;
167162
if (isAvailable)
168163
{
@@ -286,7 +281,7 @@ private void IModuleTypeLoader_LoadModuleCompleted(object sender, LoadModuleComp
286281
/// <summary>
287282
/// Handles any exception occurred in the module type loading process,
288283
/// logs the error using the <see cref="ILogger"/> and throws a <see cref="ModuleTypeLoadingException"/>.
289-
/// This method can be overridden to provide a different behavior.
284+
/// This method can be overridden to provide a different behavior.
290285
/// </summary>
291286
/// <param name="moduleInfo">The module metadata where the error happened.</param>
292287
/// <param name="exception">The exception thrown that is the cause of the current error.</param>

src/VirtoCommerce.Platform.Web/Extensions/ServiceCollectionExtensions.cs

+3-4
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@
44
using Microsoft.Extensions.DependencyInjection;
55
using Microsoft.Extensions.Hosting;
66
using Microsoft.Extensions.Logging;
7+
using Serilog;
78
using VirtoCommerce.Platform.Core.Common;
8-
using VirtoCommerce.Platform.Core.Logger;
99
using VirtoCommerce.Platform.Core.Modularity;
1010
using VirtoCommerce.Platform.Modules.External;
11+
using VirtoCommerce.Platform.Web;
1112

1213
namespace VirtoCommerce.Platform.Modules
1314
{
@@ -38,7 +39,7 @@ public static IServiceCollection AddModules(this IServiceCollection services, IM
3839
manager.Run();
3940

4041
// Ensure all modules are loaded
41-
ConsoleLog.BeginOperation("Registering API controllers");
42+
Log.ForContext<Startup>().Information("Registering API controllers");
4243

4344
var notStartedModules = moduleCatalog.Modules.Where(x => x.State == ModuleState.NotStarted);
4445
var modules = moduleCatalog.CompleteListWithDependencies(notStartedModules)
@@ -59,8 +60,6 @@ public static IServiceCollection AddModules(this IServiceCollection services, IM
5960
}
6061
}
6162

62-
ConsoleLog.EndOperation();
63-
6463
services.AddSingleton(moduleCatalog);
6564
return services;
6665
}

src/VirtoCommerce.Platform.Web/Program.cs

+1-13
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
5959
})
6060
.ConfigureServices((hostingContext, services) =>
6161
{
62-
//Conditionally use the hangFire server for this app instance to have possibility to disable processing background jobs
62+
//Conditionally use the hangFire server for this app instance to have possibility to disable processing background jobs
6363
if (hostingContext.Configuration.GetValue("VirtoCommerce:Hangfire:UseHangfireServer", true))
6464
{
6565
// Add & start hangfire server immediately.
@@ -83,18 +83,6 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
8383
}
8484
});
8585
}
86-
})
87-
.UseSerilog((context, services, loggerConfiguration) =>
88-
{
89-
// read from configuration
90-
_ = loggerConfiguration.ReadFrom.Configuration(context.Configuration);
91-
92-
// enrich configuration from external sources
93-
var configurationServices = services.GetService<IEnumerable<ILoggerConfigurationService>>();
94-
foreach (var service in configurationServices)
95-
{
96-
service.Configure(loggerConfiguration);
97-
}
9886
});
9987
}
10088
}

src/VirtoCommerce.Platform.Web/Startup.cs

+21-8
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
using Newtonsoft.Json.Converters;
3434
using OpenIddict.Abstractions;
3535
using OpenIddict.Validation.AspNetCore;
36+
using Serilog;
3637
using VirtoCommerce.Platform.Core;
3738
using VirtoCommerce.Platform.Core.Common;
3839
using VirtoCommerce.Platform.Core.DynamicProperties;
@@ -98,11 +99,26 @@ public Startup(IConfiguration configuration, IWebHostEnvironment hostingEnvironm
9899
// This method gets called by the runtime. Use this method to add services to the container.
99100
public void ConfigureServices(IServiceCollection services)
100101
{
101-
ConsoleLog.BeginOperation("Virto Commerce is loading");
102+
// Use temporary bootstrap logger (which will be replaced with configured version later) until DI initialization completed
103+
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration).CreateBootstrapLogger();
102104

103-
var databaseProvider = Configuration.GetValue("DatabaseProvider", "SqlServer");
105+
services.AddSerilog((serviceProvider, loggerConfiguration) =>
106+
{
107+
_ = loggerConfiguration.ReadFrom.Configuration(Configuration);
108+
109+
// Enrich configuration from external sources
110+
var configurationServices = serviceProvider.GetService<IEnumerable<ILoggerConfigurationService>>();
111+
foreach (var service in configurationServices)
112+
{
113+
service.Configure(loggerConfiguration);
114+
}
115+
// Preserve static logger (i.e. create new logger for DI, instead of reconfiguring existing)
116+
// to avoid exception about frozen logger because BuildServiceProvider is called multiple times
117+
}, preserveStaticLogger: true);
118+
119+
Log.ForContext<Startup>().Information("Virto Commerce is loading");
104120

105-
ConsoleLog.EndOperation();
121+
var databaseProvider = Configuration.GetValue("DatabaseProvider", "SqlServer");
106122

107123
// Optional Modules Dependecy Resolving
108124
services.Add(ServiceDescriptor.Singleton(typeof(IOptionalDependency<>), typeof(OptionalDependencyManager<>)));
@@ -301,9 +317,8 @@ public void ConfigureServices(IServiceCollection services)
301317
break;
302318
}
303319

304-
ConsoleLog.BeginOperation("Getting server certificate");
320+
Log.ForContext<Startup>().Information("Getting server certificate");
305321
ServerCertificate = GetServerCertificate(certificateLoader);
306-
ConsoleLog.EndOperation();
307322

308323
//Create backup of token handler before default claim maps are cleared
309324
// [Obsolete("Use JsonWebToken", DiagnosticId = "VC0009", UrlFormat = "https://docs.virtocommerce.org/products/products-virto3-versions/")]
@@ -671,11 +686,9 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<
671686
app.UseAutoAccountsLockoutJob(options.Value);
672687

673688
// Complete modules startup and apply their migrations
674-
ConsoleLog.BeginOperation("Post initializing modules");
689+
Log.ForContext<Startup>().Information("Post initializing modules");
675690

676691
app.UseModules();
677-
678-
ConsoleLog.EndOperation();
679692
});
680693

681694
app.UseEndpoints(SetupEndpoints);

src/VirtoCommerce.Platform.Web/appsettings.Development.json

+3-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010
"System": "Information",
1111
"Microsoft": "Information",
1212
"Microsoft.AspNetCore.SignalR": "Verbose",
13-
"Microsoft.AspNetCore.Http.Connections": "Verbose"
13+
"Microsoft.AspNetCore.Http.Connections": "Verbose",
14+
"VirtoCommerce.Platform.Modules": "Information",
15+
"VirtoCommerce.Platform.Web.Startup": "Information"
1416
}
1517
},
1618
"WriteTo": [

src/VirtoCommerce.Platform.Web/appsettings.Production.json

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
"System": "Error",
1010
"Microsoft": "Warning",
1111
"Microsoft.Hosting.Lifetime": "Information",
12+
"VirtoCommerce.Platform.Modules": "Debug",
1213
"VirtoCommerce.Platform.Web.Startup": "Information"
1314
}
1415
},

0 commit comments

Comments
 (0)