Skip to content

Commit 9ab9af6

Browse files
remove/refactor remaining references to LogManager (#5023)
* convert SC transports from NServiceBus.Logging to Microsoft.Extensions.Logging * remove signedassembly requirement so that infrastructure can be imported * revert previous change and instead propogate signing back to servicecontrol.infrastructure * fix signature of customisation classes that are dynamically created * add ilogger to test services and remove direct construction with logger * get tests to use ilogger * Switch to .NET logging * Work in progress * Remove test code * Improve logging format for storage space details * Properly shutdown NLog in Program.cs * Remove Seq logging and prepare for .NET logging migration * Update LogLevel format * Update LogLevel format in logging settings * enable adding test logging provider as part of loggerutils and create framework for settings driven logger selection * add ability to select logging provider from config * handle setting not existing * change logmanager logger factory to the standard one now used by the rest of SC * ensure logger for transport tests * domain events and persister loggers * set default to nlog and pass loglevel to test context * replace logmanager usage in persistence * cleanup remaining references to LogManager * missing files from last checkin * fix different dependency version test failure * move loggerutil setup before first static logger usage * fix different dependency version test failure --------- Co-authored-by: JasonTaylorDev <[email protected]>
1 parent c3c3de4 commit 9ab9af6

File tree

43 files changed

+258
-240
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+258
-240
lines changed

src/Directory.Packages.props

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
2525
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.1" />
2626
<PackageVersion Include="Microsoft.Extensions.Hosting.WindowsServices" Version="8.0.1" />
27+
<PackageVersion Include="Microsoft.Extensions.Logging" Version="8.0.1" />
28+
<PackageVersion Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.1" />
2729
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.3" />
2830
<PackageVersion Include="Microsoft.Extensions.TimeProvider.Testing" Version="8.10.0" />
2931
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />

src/ServiceControl.AcceptanceTesting/DiscardMessagesBehavior.cs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@ namespace ServiceControl.AcceptanceTesting
33
using System;
44
using System.Linq;
55
using System.Threading.Tasks;
6+
using Microsoft.Extensions.Logging;
67
using NServiceBus;
78
using NServiceBus.AcceptanceTesting;
8-
using NServiceBus.Logging;
99
using NServiceBus.Pipeline;
10+
using ServiceControl.Infrastructure;
1011

1112
public class DiscardMessagesBehavior : IBehavior<ITransportReceiveContext, ITransportReceiveContext>
1213
{
@@ -44,15 +45,20 @@ public Task Invoke(ITransportReceiveContext context, Func<ITransportReceiveConte
4445
{
4546
context.Message.Headers.TryGetValue(Headers.MessageId, out var originalMessageId);
4647
context.Message.Headers.TryGetValue(Headers.EnclosedMessageTypes, out var enclosedMessageTypes);
47-
log.Debug($"Discarding message '{context.Message.MessageId}'({originalMessageId ?? string.Empty}) because it's session id is '{session}' instead of '{currentSession}' Message Types: {enclosedMessageTypes}.");
48+
var logger = LoggerUtil.CreateStaticLogger<DiscardMessagesBehavior>();
49+
logger.LogDebug("Discarding message '{MessageId}'({OriginalMessageId}) because it's session id is '{MessageSessionId}' instead of '{CurrentSessionId}' Message Types: {EnclosedMessageTypes}.",
50+
context.Message.MessageId,
51+
originalMessageId ?? string.Empty,
52+
session,
53+
currentSession,
54+
enclosedMessageTypes);
4855
return Task.CompletedTask;
4956
}
5057

5158
return next(context);
5259
}
5360

5461
ScenarioContext scenarioContext;
55-
static ILog log = LogManager.GetLogger<DiscardMessagesBehavior>();
5662

5763
static string[] pluginMessages =
5864
{

src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ async Task InitializeServiceControl(ScenarioContext context)
5050
var logPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
5151
Directory.CreateDirectory(logPath);
5252
var loggingSettings = new LoggingSettings(Settings.SettingsRootNamespace, defaultLevel: LogLevel.Debug, logPath: logPath);
53+
LoggerUtil.ActiveLoggers = Loggers.Test;
5354

5455
var settings = new Settings(transportToUse.TypeName, persistenceToUse.PersistenceType, loggingSettings, forwardErrorMessages: false, errorRetentionPeriod: TimeSpan.FromDays(10))
5556
{
@@ -65,9 +66,9 @@ async Task InitializeServiceControl(ScenarioContext context)
6566
{
6667
var headers = messageContext.Headers;
6768
var id = messageContext.NativeMessageId;
68-
var log = NServiceBus.Logging.LogManager.GetLogger<ServiceControlComponentRunner>();
69+
var logger = LoggerUtil.CreateStaticLogger<ServiceControlComponentRunner>(loggingSettings.LogLevel);
6970
headers.TryGetValue(Headers.MessageId, out var originalMessageId);
70-
log.Debug($"OnMessage for message '{id}'({originalMessageId ?? string.Empty}).");
71+
logger.LogDebug("OnMessage for message '{MessageId}'({OriginalMessageId})", id, originalMessageId ?? string.Empty);
7172

7273
//Do not filter out CC, SA and HB messages as they can't be stamped
7374
if (headers.TryGetValue(Headers.EnclosedMessageTypes, out var messageTypes)
@@ -86,7 +87,7 @@ async Task InitializeServiceControl(ScenarioContext context)
8687
var currentSession = context.TestRunId.ToString();
8788
if (!headers.TryGetValue("SC.SessionID", out var session) || session != currentSession)
8889
{
89-
log.Debug($"Discarding message '{id}'({originalMessageId ?? string.Empty}) because it's session id is '{session}' instead of '{currentSession}'.");
90+
logger.LogDebug("Discarding message '{MessageId}'({OriginalMessageId}) because it's session id is '{SessionId}' instead of '{CurrentSessionId}'", id, originalMessageId ?? string.Empty, session, currentSession);
9091
return true;
9192
}
9293

src/ServiceControl.Audit.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ async Task InitializeServiceControl(ScenarioContext context)
4545
Directory.CreateDirectory(logPath);
4646

4747
var loggingSettings = new LoggingSettings(Settings.SettingsRootNamespace, defaultLevel: LogLevel.Debug, logPath: logPath);
48+
LoggerUtil.ActiveLoggers = Loggers.Test;
4849

4950
settings = new Settings(transportToUse.TypeName, persistenceToUse.PersistenceType, loggingSettings)
5051
{
@@ -56,9 +57,9 @@ async Task InitializeServiceControl(ScenarioContext context)
5657
{
5758
var id = messageContext.NativeMessageId;
5859
var headers = messageContext.Headers;
59-
var log = LoggerUtil.CreateStaticLogger<ServiceControlComponentRunner>();
60+
var logger = LoggerUtil.CreateStaticLogger<ServiceControlComponentRunner>(loggingSettings.LogLevel);
6061
headers.TryGetValue(Headers.MessageId, out var originalMessageId);
61-
log.LogDebug("OnMessage for message '{MessageId}'({OriginalMessageId}).", id, originalMessageId ?? string.Empty);
62+
logger.LogDebug("OnMessage for message '{MessageId}'({OriginalMessageId}).", id, originalMessageId ?? string.Empty);
6263

6364
//Do not filter out CC, SA and HB messages as they can't be stamped
6465
if (headers.TryGetValue(Headers.EnclosedMessageTypes, out var messageTypes)
@@ -77,7 +78,7 @@ async Task InitializeServiceControl(ScenarioContext context)
7778
var currentSession = context.TestRunId.ToString();
7879
if (!headers.TryGetValue("SC.SessionID", out var session) || session != currentSession)
7980
{
80-
log.LogDebug("Discarding message '{MessageId}'({OriginalMessageId}) because it's session id is '{SessionId}' instead of '{CurrentSessionId}'.", id, originalMessageId ?? string.Empty, session, currentSession);
81+
logger.LogDebug("Discarding message '{MessageId}'({OriginalMessageId}) because it's session id is '{SessionId}' instead of '{CurrentSessionId}'.", id, originalMessageId ?? string.Empty, session, currentSession);
8182
return true;
8283
}
8384

src/ServiceControl.Audit.Persistence.RavenDB/RavenPersistenceConfiguration.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ internal static DatabaseConfiguration GetDatabaseConfiguration(PersistenceSettin
108108

109109
if (settings.PersisterSpecificSettings.TryGetValue(RavenDbLogLevelKey, out var ravenDbLogLevel))
110110
{
111-
logsMode = RavenDbLogLevelToLogsModeMapper.Map(ravenDbLogLevel);
111+
logsMode = RavenDbLogLevelToLogsModeMapper.Map(ravenDbLogLevel, Logger);
112112
}
113113

114114
serverConfiguration = new ServerConfiguration(dbPath, serverUrl, logPath, logsMode);

src/ServiceControl.DomainEvents/DomainEvents.cs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,10 @@
44
using System.Threading;
55
using System.Threading.Tasks;
66
using Microsoft.Extensions.DependencyInjection;
7-
using NServiceBus.Logging;
7+
using Microsoft.Extensions.Logging;
88

9-
public class DomainEvents : IDomainEvents
9+
public class DomainEvents(IServiceProvider serviceProvider, ILogger<DomainEvents> logger) : IDomainEvents
1010
{
11-
static readonly ILog Log = LogManager.GetLogger<DomainEvents>();
12-
13-
readonly IServiceProvider serviceProvider;
14-
public DomainEvents(IServiceProvider serviceProvider) => this.serviceProvider = serviceProvider;
15-
1611
public async Task Raise<T>(T domainEvent, CancellationToken cancellationToken) where T : IDomainEvent
1712
{
1813
var handlers = serviceProvider.GetServices<IDomainHandler<T>>();
@@ -25,7 +20,7 @@ await handler.Handle(domainEvent, cancellationToken)
2520
}
2621
catch (Exception e)
2722
{
28-
Log.Error($"Unexpected error publishing domain event {typeof(T)}", e);
23+
logger.LogError(e, "Unexpected error publishing domain event {EventType}", typeof(T));
2924
throw;
3025
}
3126
}
@@ -40,7 +35,7 @@ await handler.Handle(domainEvent, cancellationToken)
4035
}
4136
catch (Exception e)
4237
{
43-
Log.Error($"Unexpected error publishing domain event {typeof(T)}", e);
38+
logger.LogError(e, "Unexpected error publishing domain event {EventType}", typeof(T));
4439
throw;
4540
}
4641
}

src/ServiceControl.DomainEvents/ServiceControl.DomainEvents.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
<ItemGroup>
88
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
9+
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
910
<PackageReference Include="NServiceBus" />
1011
</ItemGroup>
1112

src/ServiceControl.Infrastructure/LoggerUtil.cs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,22 @@ public static class LoggerUtil
1919
{
2020
public static Loggers ActiveLoggers { private get; set; } = Loggers.None;
2121

22+
public static bool IsLoggingTo(Loggers logger)
23+
{
24+
return (logger & ActiveLoggers) == logger;
25+
}
26+
2227
public static void BuildLogger(this ILoggingBuilder loggingBuilder, LogLevel level)
2328
{
24-
if ((Loggers.Test & ActiveLoggers) == Loggers.Test)
29+
if (IsLoggingTo(Loggers.Test))
2530
{
26-
loggingBuilder.Services.AddSingleton<ILoggerProvider>(new TestContextProvider());
31+
loggingBuilder.Services.AddSingleton<ILoggerProvider>(new TestContextProvider(level));
2732
}
28-
if ((Loggers.NLog & ActiveLoggers) == Loggers.NLog)
33+
if (IsLoggingTo(Loggers.NLog))
2934
{
3035
loggingBuilder.AddNLog();
3136
}
32-
if ((Loggers.Seq & ActiveLoggers) == Loggers.Seq)
37+
if (IsLoggingTo(Loggers.Seq))
3338
{
3439
loggingBuilder.AddSeq();
3540
}

src/ServiceControl.Infrastructure/LoggingConfigurator.cs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,19 @@ namespace ServiceControl.Infrastructure
1212
using LogManager = NServiceBus.Logging.LogManager;
1313
using LogLevel = NLog.LogLevel;
1414

15-
// TODO: Migrate from NLog to .NET logging
1615
public static class LoggingConfigurator
1716
{
1817
public static void ConfigureLogging(LoggingSettings loggingSettings)
1918
{
20-
if (NLog.LogManager.Configuration != null)
19+
//used for loggers outside of ServiceControl (i.e. transports and core) to use the logger factory defined here
20+
LogManager.UseFactory(new ExtensionsLoggerFactory(LoggerFactory.Create(configure => configure.BuildLogger(loggingSettings.LogLevel))));
21+
22+
if (!LoggerUtil.IsLoggingTo(Loggers.NLog) || NLog.LogManager.Configuration != null)
2123
{
2224
return;
2325
}
2426

27+
//configure NLog
2528
var nlogConfig = new LoggingConfiguration();
2629
var simpleLayout = new SimpleLayout("${longdate}|${processtime}|${threadid}|${level}|${logger}|${message}${onexception:|${exception:format=tostring}}");
2730

@@ -76,8 +79,7 @@ public static void ConfigureLogging(LoggingSettings loggingSettings)
7679

7780
NLog.LogManager.Configuration = nlogConfig;
7881

79-
LogManager.UseFactory(new ExtensionsLoggerFactory(LoggerFactory.Create(configure => configure.BuildLogger(loggingSettings.LogLevel))));
80-
82+
//using LogManager here rather than LoggerUtil.CreateStaticLogger since this is exclusive to NLog
8183
var logger = LogManager.GetLogger("LoggingConfiguration");
8284
var logEventInfo = new LogEventInfo { TimeStamp = DateTime.UtcNow };
8385
var loggingTo = AppEnvironment.RunningInContainer ? "console" : fileTarget.FileName.Render(logEventInfo);

src/ServiceControl.Infrastructure/LoggingSettings.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,6 @@ public class LoggingSettings
1111
{
1212
public LoggingSettings(SettingsRootNamespace rootNamespace, LogLevel defaultLevel = LogLevel.Information, string logPath = null)
1313
{
14-
LogLevel = InitializeLogLevel(rootNamespace, defaultLevel);
15-
LogPath = SettingsReader.Read(rootNamespace, logPathKey, Environment.ExpandEnvironmentVariables(logPath ?? DefaultLogLocation()));
16-
1714
var loggingProviders = (SettingsReader.Read<string>(rootNamespace, loggingProvidersKey) ?? "").Split(",");
1815
var activeLoggers = Loggers.None;
1916
if (loggingProviders.Contains("NLog"))
@@ -26,6 +23,9 @@ public LoggingSettings(SettingsRootNamespace rootNamespace, LogLevel defaultLeve
2623
}
2724
//this defaults to NLog because historically that was the default, and we don't want to break existing installs that don't have the config key to define loggingProviders
2825
LoggerUtil.ActiveLoggers = activeLoggers == Loggers.None ? Loggers.NLog : activeLoggers;
26+
27+
LogLevel = InitializeLogLevel(rootNamespace, defaultLevel);
28+
LogPath = SettingsReader.Read(rootNamespace, logPathKey, Environment.ExpandEnvironmentVariables(logPath ?? DefaultLogLocation()));
2929
}
3030

3131
public LogLevel LogLevel { get; }

0 commit comments

Comments
 (0)