Skip to content

Commit 007ef79

Browse files
authored
convert SC loggers to ILogger (#5000)
included Seq and Otel as options on top on NLog
1 parent 213327d commit 007ef79

File tree

179 files changed

+1429
-1281
lines changed

Some content is hidden

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

179 files changed

+1429
-1281
lines changed

src/Directory.Packages.props

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@
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" />
29+
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.3" />
2730
<PackageVersion Include="Microsoft.Extensions.TimeProvider.Testing" Version="8.10.0" />
2831
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
2932
<PackageVersion Include="Microsoft-WindowsAPICodePack-Shell" Version="1.1.5" />
@@ -63,6 +66,7 @@
6366
<PackageVersion Include="PublicApiGenerator" Version="11.4.6" />
6467
<PackageVersion Include="RavenDB.Embedded" Version="6.2.6" />
6568
<PackageVersion Include="ReactiveUI.WPF" Version="20.1.63" />
69+
<PackageVersion Include="Seq.Extensions.Logging" Version="8.0.0" />
6670
<PackageVersion Include="ServiceControl.Contracts" Version="5.0.0" />
6771
<PackageVersion Include="System.Configuration.ConfigurationManager" Version="8.0.1" />
6872
<PackageVersion Include="System.Diagnostics.PerformanceCounter" Version="8.0.1" />

src/Particular.LicensingComponent/AuditThroughput/AuditThroughputCollectorHostedService.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public class AuditThroughputCollectorHostedService(
2020

2121
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
2222
{
23-
logger.LogInformation($"Starting {nameof(AuditThroughputCollectorHostedService)}");
23+
logger.LogInformation("Starting {ServiceName}", nameof(AuditThroughputCollectorHostedService));
2424

2525
try
2626
{
@@ -42,14 +42,14 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken)
4242
}
4343
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
4444
{
45-
logger.LogInformation($"Stopping {nameof(AuditThroughputCollectorHostedService)}");
45+
logger.LogInformation("Stopping {ServiceName}", nameof(AuditThroughputCollectorHostedService));
4646
}
4747
}
4848

4949
async Task GatherThroughput(CancellationToken cancellationToken)
5050
{
5151
var utcYesterday = DateOnly.FromDateTime(timeProvider.GetUtcNow().DateTime).AddDays(-1);
52-
logger.LogInformation($"Gathering throughput from audit for {utcYesterday.ToShortDateString()}");
52+
logger.LogInformation("Gathering throughput from audit for {AuditDate}", utcYesterday.ToShortDateString());
5353

5454
await VerifyAuditInstances(cancellationToken);
5555

@@ -59,7 +59,7 @@ async Task GatherThroughput(CancellationToken cancellationToken)
5959

6060
if (!knownEndpoints.Any())
6161
{
62-
logger.LogWarning("No known endpoints could be found.");
62+
logger.LogWarning("No known endpoints could be found");
6363
}
6464

6565
foreach (var tuple in await dataStore.GetEndpoints([.. knownEndpointsLookup.Keys], cancellationToken))
@@ -115,18 +115,18 @@ async Task VerifyAuditInstances(CancellationToken cancellationToken)
115115
{
116116
if (remote.Status == "online" || remote.SemanticVersion is not null)
117117
{
118-
logger.LogInformation($"ServiceControl Audit instance at {remote.ApiUri} detected running version {remote.SemanticVersion}");
118+
logger.LogInformation("ServiceControl Audit instance at {RemoteApiUri} detected running version {RemoteSemanticVersion}", remote.ApiUri, remote.SemanticVersion);
119119
}
120120
else
121121
{
122-
logger.LogWarning($"Unable to determine the version of one or more ServiceControl Audit instances. For the instance with URI {remote.ApiUri}, the status was '{remote.Status}' and the version string returned was '{remote.VersionString}'.");
122+
logger.LogWarning("Unable to determine the version of one or more ServiceControl Audit instances. For the instance with URI {RemoteApiUri}, the status was '{RemoteStatus}' and the version string returned was '{RemoteVersionString}'", remote.ApiUri, remote.Status, remote.VersionString);
123123
}
124124
}
125125

126126
var allHaveAuditCounts = remotesInfo.All(auditQuery.ValidRemoteInstances);
127127
if (!allHaveAuditCounts)
128128
{
129-
logger.LogWarning($"At least one ServiceControl Audit instance is either not running the required version ({auditQuery.MinAuditCountsVersion}) or is not configured for at least 2 days of retention. Audit throughput will not be available.");
129+
logger.LogWarning("At least one ServiceControl Audit instance is either not running the required version ({RequiredAuditVersion}) or is not configured for at least 2 days of retention. Audit throughput will not be available", auditQuery.MinAuditCountsVersion);
130130
}
131131
}
132132

src/Particular.LicensingComponent/BrokerThroughput/BrokerThroughputCollectorHostedService.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,11 @@ static ReadOnlyDictionary<string, string> LoadBrokerSettingValues(IEnumerable<Ke
2929

3030
if (brokerThroughputQuery.HasInitialisationErrors(out var errorMessage))
3131
{
32-
logger.LogError($"Could not start {nameof(BrokerThroughputCollectorHostedService)}, due to initialisation errors:\n{errorMessage}");
32+
logger.LogError("Could not start {ServiceName}, due to initialisation errors:\n{InitializationErrors}", nameof(BrokerThroughputCollectorHostedService), errorMessage);
3333
return;
3434
}
3535

36-
logger.LogInformation($"Starting {nameof(BrokerThroughputCollectorHostedService)}");
36+
logger.LogInformation("Starting {ServiceName}", nameof(BrokerThroughputCollectorHostedService));
3737

3838
try
3939
{
@@ -55,7 +55,7 @@ static ReadOnlyDictionary<string, string> LoadBrokerSettingValues(IEnumerable<Ke
5555
}
5656
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
5757
{
58-
logger.LogInformation($"Stopping {nameof(BrokerThroughputCollectorHostedService)}");
58+
logger.LogInformation("Stopping {ServiceName}", nameof(BrokerThroughputCollectorHostedService));
5959
}
6060
}
6161

src/Particular.LicensingComponent/MonitoringThroughput/MonitoringThroughputHostedService.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,15 @@ async Task Handle(MessageContext message, CancellationToken cancellationToken)
2424

2525
public async Task StartAsync(CancellationToken cancellationToken)
2626
{
27-
logger.LogInformation($"Starting {nameof(MonitoringThroughputHostedService)}");
27+
logger.LogInformation("Starting {ServiceName}", nameof(MonitoringThroughputHostedService));
2828

2929
transportInfrastructure = await transportCustomization.CreateTransportInfrastructure(ServiceControlSettings.ServiceControlThroughputDataQueue, transportSettings, Handle, (_, __) => Task.FromResult(ErrorHandleResult.Handled), (_, __) => Task.CompletedTask);
3030
await transportInfrastructure.Receivers[ServiceControlSettings.ServiceControlThroughputDataQueue].StartReceive(cancellationToken);
3131
}
3232

3333
public async Task StopAsync(CancellationToken cancellationToken)
3434
{
35-
logger.LogInformation($"Stopping {nameof(MonitoringThroughputHostedService)}");
35+
logger.LogInformation("Stopping {ServiceName}", nameof(MonitoringThroughputHostedService));
3636

3737
if (transportInfrastructure != null)
3838
{

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.RavenDB/StartupModeTests.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Threading.Tasks;
66
using Hosting.Commands;
77
using Microsoft.Extensions.Hosting;
8+
using Microsoft.Extensions.Logging.Abstractions;
89
using NServiceBus;
910
using NUnit.Framework;
1011
using Particular.ServiceControl.Hosting;
@@ -57,7 +58,7 @@ public async Task CanRunMaintenanceMode()
5758
public async Task CanRunImportFailedMessagesMode()
5859
=> await new TestableImportFailedErrorsCommand().Execute(new HostArguments(Array.Empty<string>()), settings);
5960

60-
class TestableImportFailedErrorsCommand : ImportFailedErrorsCommand
61+
class TestableImportFailedErrorsCommand() : ImportFailedErrorsCommand()
6162
{
6263
protected override EndpointConfiguration CreateEndpointConfiguration(Settings settings)
6364
{

src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_a_retry_fails_to_be_sent.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using AcceptanceTesting.EndpointTemplates;
99
using Infrastructure;
1010
using Microsoft.Extensions.DependencyInjection;
11+
using Microsoft.Extensions.Logging.Abstractions;
1112
using NServiceBus;
1213
using NServiceBus.AcceptanceTesting;
1314
using NServiceBus.Routing;
@@ -146,7 +147,7 @@ public class MyContext : ScenarioContext
146147
public class MessageThatWillFail : ICommand;
147148

148149
public class FakeReturnToSender(IErrorMessageDataStore errorMessageStore, MyContext myContext)
149-
: ReturnToSender(errorMessageStore)
150+
: ReturnToSender(errorMessageStore, NullLogger<ReturnToSender>.Instance)
150151
{
151152
public override Task HandleMessage(MessageContext message, IMessageDispatcher sender, string errorQueueTransportAddress, CancellationToken cancellationToken = default)
152153
{

src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
using Microsoft.AspNetCore.TestHost;
1616
using Microsoft.Extensions.DependencyInjection;
1717
using Microsoft.Extensions.Hosting;
18-
using NLog;
18+
using Microsoft.Extensions.Logging;
1919
using NServiceBus;
2020
using NServiceBus.AcceptanceTesting;
2121
using NServiceBus.AcceptanceTesting.Support;
@@ -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: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ namespace ServiceControl.Audit.AcceptanceTests.TestSupport
1717
using Microsoft.AspNetCore.Builder;
1818
using Microsoft.AspNetCore.TestHost;
1919
using Microsoft.Extensions.Hosting;
20+
using Microsoft.Extensions.Logging;
2021
using NServiceBus;
2122
using NServiceBus.AcceptanceTesting;
2223
using NServiceBus.AcceptanceTesting.Support;
@@ -43,7 +44,8 @@ async Task InitializeServiceControl(ScenarioContext context)
4344
var logPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
4445
Directory.CreateDirectory(logPath);
4546

46-
var loggingSettings = new LoggingSettings(Settings.SettingsRootNamespace, defaultLevel: NLog.LogLevel.Debug, logPath: logPath);
47+
var loggingSettings = new LoggingSettings(Settings.SettingsRootNamespace, defaultLevel: LogLevel.Debug, logPath: logPath);
48+
LoggerUtil.ActiveLoggers = Loggers.Test;
4749

4850
settings = new Settings(transportToUse.TypeName, persistenceToUse.PersistenceType, loggingSettings)
4951
{
@@ -55,9 +57,9 @@ async Task InitializeServiceControl(ScenarioContext context)
5557
{
5658
var id = messageContext.NativeMessageId;
5759
var headers = messageContext.Headers;
58-
var log = NServiceBus.Logging.LogManager.GetLogger<ServiceControlComponentRunner>();
60+
var logger = LoggerUtil.CreateStaticLogger<ServiceControlComponentRunner>(loggingSettings.LogLevel);
5961
headers.TryGetValue(Headers.MessageId, out var originalMessageId);
60-
log.Debug($"OnMessage for message '{id}'({originalMessageId ?? string.Empty}).");
62+
logger.LogDebug("OnMessage for message '{MessageId}'({OriginalMessageId})", id, originalMessageId ?? string.Empty);
6163

6264
//Do not filter out CC, SA and HB messages as they can't be stamped
6365
if (headers.TryGetValue(Headers.EnclosedMessageTypes, out var messageTypes)
@@ -76,7 +78,7 @@ async Task InitializeServiceControl(ScenarioContext context)
7678
var currentSession = context.TestRunId.ToString();
7779
if (!headers.TryGetValue("SC.SessionID", out var session) || session != currentSession)
7880
{
79-
log.Debug($"Discarding message '{id}'({originalMessageId ?? string.Empty}) because it's session id is '{session}' instead of '{currentSession}'.");
81+
logger.LogDebug("Discarding message '{MessageId}'({OriginalMessageId}) because it's session id is '{SessionId}' instead of '{CurrentSessionId}'", id, originalMessageId ?? string.Empty, session, currentSession);
8082
return true;
8183
}
8284

src/ServiceControl.Audit.Persistence.InMemory/InMemoryAuditIngestionUnitOfWorkFactory.cs

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,14 @@
55
using ServiceControl.Audit.Auditing.BodyStorage;
66
using ServiceControl.Audit.Persistence.UnitOfWork;
77

8-
class InMemoryAuditIngestionUnitOfWorkFactory : IAuditIngestionUnitOfWorkFactory
8+
class InMemoryAuditIngestionUnitOfWorkFactory(InMemoryAuditDataStore dataStore, BodyStorageEnricher bodyStorageEnricher) : IAuditIngestionUnitOfWorkFactory
99
{
10-
public InMemoryAuditIngestionUnitOfWorkFactory(InMemoryAuditDataStore dataStore, IBodyStorage bodyStorage, PersistenceSettings settings)
11-
{
12-
this.dataStore = dataStore;
13-
bodyStorageEnricher = new BodyStorageEnricher(bodyStorage, settings);
14-
}
15-
1610
public ValueTask<IAuditIngestionUnitOfWork> StartNew(int batchSize, CancellationToken cancellationToken)
1711
{
1812
//The batchSize argument is ignored: the in-memory storage implementation doesn't support batching.
1913
return new ValueTask<IAuditIngestionUnitOfWork>(new InMemoryAuditIngestionUnitOfWork(dataStore, bodyStorageEnricher));
2014
}
2115

2216
public bool CanIngestMore() => true;
23-
24-
InMemoryAuditDataStore dataStore;
25-
BodyStorageEnricher bodyStorageEnricher;
2617
}
2718
}

0 commit comments

Comments
 (0)