Skip to content

Commit a47d8ec

Browse files
committed
convert audit loggers to ILogger
1 parent 2629e6d commit a47d8ec

File tree

26 files changed

+171
-155
lines changed

26 files changed

+171
-155
lines changed

src/Directory.Packages.props

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
<PackageVersion Include="PublicApiGenerator" Version="11.4.6" />
6464
<PackageVersion Include="RavenDB.Embedded" Version="6.2.5" />
6565
<PackageVersion Include="ReactiveUI.WPF" Version="20.1.63" />
66+
<PackageVersion Include="Seq.Extensions.Logging" Version="8.0.0" />
6667
<PackageVersion Include="ServiceControl.Contracts" Version="5.0.0" />
6768
<PackageVersion Include="System.Configuration.ConfigurationManager" Version="8.0.1" />
6869
<PackageVersion Include="System.Diagnostics.PerformanceCounter" Version="8.0.1" />
@@ -91,4 +92,4 @@
9192
<GlobalPackageReference Include="Microsoft.Build.CopyOnWrite" Version="1.0.334" />
9293
<GlobalPackageReference Include="Particular.Packaging" Version="4.2.2" />
9394
</ItemGroup>
94-
</Project>
95+
</Project>

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ async Task InitializeServiceControl(ScenarioContext context)
9898

9999
using (new DiagnosticTimer($"Creating infrastructure for {instanceName}"))
100100
{
101-
var setupCommand = new SetupCommand();
101+
var setupCommand = new SetupCommand(LoggerUtil.CreateStaticLogger<SetupCommand>());
102102
await setupCommand.Execute(new HostArguments([]), settings);
103103
}
104104

src/ServiceControl.Audit.UnitTests/Infrastructure/When_instance_is_setup.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
using NServiceBus;
1313
using NServiceBus.Transport;
1414
using NUnit.Framework;
15+
using ServiceControl.Infrastructure;
1516
using Transports;
1617

1718
class When_instance_is_setup
@@ -41,7 +42,7 @@ public async Task Should_provision_queues()
4142
AssemblyLoadContextResolver = static _ => AssemblyLoadContext.Default
4243
};
4344

44-
var setupCommand = new SetupCommand();
45+
var setupCommand = new SetupCommand(LoggerUtil.CreateStaticLogger<SetupCommand>());
4546
await setupCommand.Execute(new HostArguments([]), settings);
4647

4748
Assert.That(FakeTransport.QueuesCreated, Is.EquivalentTo(new[]

src/ServiceControl.Audit/App.config

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ These settings are only here so that we can debug ServiceControl while developin
99
<add key="ServiceControl.Audit/HostName" value="localhost" />
1010
<add key="ServiceControl.Audit/DatabaseMaintenancePort" value="44445" />
1111
<!-- DEVS - Pick a transport to run Auditing instance on -->
12-
<add key="ServiceControl.Audit/TransportType" value="LearningTransport" />
12+
<!--<add key="ServiceControl.Audit/TransportType" value="LearningTransport" />-->
1313
<!--<add key="ServiceControl.Audit/TransportType" value="AmazonSQS" />-->
1414
<!--<add key="ServiceControl.Audit/TransportType" value="AzureStorageQueue" />-->
1515
<!--<add key="ServiceControl.Audit/TransportType" value="MSMQ" />-->
1616
<!--<add key="ServiceControl.Audit/TransportType" value="NetStandardAzureServiceBus" />-->
1717
<!--<add key="ServiceControl.Audit/TransportType" value="PostgreSQL" />-->
18-
<!--<add key="ServiceControl.Audit/TransportType" value="RabbitMQ.QuorumConventionalRouting" />-->
18+
<add key="ServiceControl.Audit/TransportType" value="RabbitMQ.QuorumConventionalRouting" />
1919
<!--<add key="ServiceControl.Audit/TransportType" value="SQLServer" />-->
2020

2121
<!-- DEVS - Pick a persistence to run Auditing instance on. -->
@@ -27,7 +27,7 @@ These settings are only here so that we can debug ServiceControl while developin
2727

2828
<!-- Learning -->
2929
<!-- If the LearningTransport connectionString is empty, it will default to the solution directory when running/debugging from the IDE -->
30-
<add name="NServiceBus/Transport" connectionString="" />
30+
<!--<add name="NServiceBus/Transport" connectionString="" />-->
3131

3232
<!--Amazon SQS -->
3333
<!--<add name="NServiceBus/Transport" connectionString="Region=;QueueNamePrefix=;TopicNamePrefix=;AccessKeyId=;SecretAccessKey=;S3BucketForLargeMessages=;S3KeyPrefix=" />-->
@@ -46,6 +46,7 @@ These settings are only here so that we can debug ServiceControl while developin
4646

4747
<!--RabbitMQ.QuorumConventionalRouting -->
4848
<!--<add name="NServiceBus/Transport" connectionString="host=;username=;password=" />-->
49+
<add name="NServiceBus/Transport" connectionString="host=localhost:7672;username=guest;password=guest;ManagementApiUrl=http://localhost:17672" />
4950

5051
<!--SQLServer -->
5152
<!--<add name="NServiceBus/Transport" connectionString="Data Source=;Initial Catalog=nservicebus;Integrated Security=True;Queue Schema=myschema;Subscriptions Table=tablename@schema@catalog" />-->

src/ServiceControl.Audit/Auditing/AuditIngestion.cs

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
using Infrastructure.Settings;
99
using Metrics;
1010
using Microsoft.Extensions.Hosting;
11+
using Microsoft.Extensions.Logging;
1112
using NServiceBus;
12-
using NServiceBus.Logging;
1313
using NServiceBus.Transport;
1414
using Persistence;
1515
using Persistence.UnitOfWork;
@@ -27,7 +27,8 @@ public AuditIngestion(
2727
AuditIngestor auditIngestor,
2828
IAuditIngestionUnitOfWorkFactory unitOfWorkFactory,
2929
IHostApplicationLifetime applicationLifetime,
30-
IngestionMetrics metrics
30+
IngestionMetrics metrics,
31+
ILogger<AuditIngestion> logger
3132
)
3233
{
3334
inputEndpoint = settings.AuditQueue;
@@ -38,7 +39,7 @@ IngestionMetrics metrics
3839
this.settings = settings;
3940
this.applicationLifetime = applicationLifetime;
4041
this.metrics = metrics;
41-
42+
this.logger = logger;
4243
if (!transportSettings.MaxConcurrency.HasValue)
4344
{
4445
throw new ArgumentException("MaxConcurrency is not set in TransportSettings");
@@ -54,7 +55,7 @@ IngestionMetrics metrics
5455
FullMode = BoundedChannelFullMode.Wait
5556
});
5657

57-
errorHandlingPolicy = new AuditIngestionFaultPolicy(failedImportsStorage, settings.LoggingSettings, OnCriticalError, metrics);
58+
errorHandlingPolicy = new AuditIngestionFaultPolicy(failedImportsStorage, settings.LoggingSettings, OnCriticalError, metrics, logger);
5859

5960
watchdog = new Watchdog(
6061
"audit message ingestion",
@@ -69,7 +70,7 @@ IngestionMetrics metrics
6970

7071
Task OnCriticalError(string failure, Exception exception)
7172
{
72-
logger.Fatal($"OnCriticalError. '{failure}'", exception);
73+
logger.LogCritical(exception, "OnCriticalError. '{failure}'", failure);
7374
return watchdog.OnFailure(failure);
7475
}
7576

@@ -81,7 +82,7 @@ async Task EnsureStarted(CancellationToken cancellationToken)
8182

8283
var canIngest = unitOfWorkFactory.CanIngestMore();
8384

84-
logger.DebugFormat("Ensure started {0}", canIngest);
85+
logger.LogDebug("Ensure started {canIngest}", canIngest);
8586

8687
if (canIngest)
8788
{
@@ -115,13 +116,13 @@ async Task SetUpAndStartInfrastructure(CancellationToken cancellationToken)
115116
{
116117
if (messageReceiver != null)
117118
{
118-
logger.Debug("Infrastructure already Started");
119+
logger.LogDebug("Infrastructure already Started");
119120
return;
120121
}
121122

122123
try
123124
{
124-
logger.Info("Starting infrastructure");
125+
logger.LogInformation("Starting infrastructure");
125126
transportInfrastructure = await transportCustomization.CreateTransportInfrastructure(
126127
inputEndpoint,
127128
transportSettings,
@@ -136,11 +137,11 @@ async Task SetUpAndStartInfrastructure(CancellationToken cancellationToken)
136137
await auditIngestor.VerifyCanReachForwardingAddress(cancellationToken);
137138
await messageReceiver.StartReceive(cancellationToken);
138139

139-
logger.Info(LogMessages.StartedInfrastructure);
140+
logger.LogInformation(LogMessages.StartedInfrastructure);
140141
}
141142
catch (Exception e)
142143
{
143-
logger.Error("Failed to start infrastructure", e);
144+
logger.LogError(e, "Failed to start infrastructure");
144145
throw;
145146
}
146147
}
@@ -149,13 +150,13 @@ async Task StopAndTeardownInfrastructure(CancellationToken cancellationToken)
149150
{
150151
if (transportInfrastructure == null)
151152
{
152-
logger.Debug("Infrastructure already Stopped");
153+
logger.LogDebug("Infrastructure already Stopped");
153154
return;
154155
}
155156

156157
try
157158
{
158-
logger.Info("Stopping infrastructure");
159+
logger.LogInformation("Stopping infrastructure");
159160
try
160161
{
161162
if (messageReceiver != null)
@@ -171,11 +172,11 @@ async Task StopAndTeardownInfrastructure(CancellationToken cancellationToken)
171172
messageReceiver = null;
172173
transportInfrastructure = null;
173174

174-
logger.Info(LogMessages.StoppedInfrastructure);
175+
logger.LogInformation(LogMessages.StoppedInfrastructure);
175176
}
176177
catch (Exception e)
177178
{
178-
logger.Error("Failed to stop infrastructure", e);
179+
logger.LogError(e, "Failed to stop infrastructure");
179180
throw;
180181
}
181182
}
@@ -254,11 +255,11 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
254255

255256
if (e is OperationCanceledException && stoppingToken.IsCancellationRequested)
256257
{
257-
logger.Info("Batch cancelled", e);
258+
logger.LogInformation(e, "Batch cancelled");
258259
break;
259260
}
260261

261-
logger.Info("Ingesting messages failed", e);
262+
logger.LogInformation(e, "Ingesting messages failed");
262263
}
263264
finally
264265
{
@@ -291,7 +292,7 @@ public override async Task StopAsync(CancellationToken cancellationToken)
291292
}
292293
catch (OperationCanceledException e) when (cancellationToken.IsCancellationRequested)
293294
{
294-
logger.Info("Shutdown cancelled", e);
295+
logger.LogInformation(e, "Shutdown cancelled");
295296
}
296297
}
297298
}
@@ -313,8 +314,7 @@ public override async Task StopAsync(CancellationToken cancellationToken)
313314
readonly Watchdog watchdog;
314315
readonly IHostApplicationLifetime applicationLifetime;
315316
readonly IngestionMetrics metrics;
316-
317-
static readonly ILog logger = LogManager.GetLogger<AuditIngestion>();
317+
readonly ILogger<AuditIngestion> logger;
318318

319319
internal static class LogMessages
320320
{

src/ServiceControl.Audit/Auditing/AuditIngestionFaultPolicy.cs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,21 +7,27 @@
77
using System.Runtime.Versioning;
88
using System.Threading;
99
using System.Threading.Tasks;
10+
using Configuration;
1011
using Infrastructure;
11-
using NServiceBus.Logging;
12+
using Metrics;
13+
using Microsoft.Extensions.Logging;
1214
using NServiceBus.Transport;
1315
using Persistence;
14-
using Configuration;
15-
using Metrics;
1616
using ServiceControl.Infrastructure;
1717

1818
class AuditIngestionFaultPolicy
1919
{
20-
public AuditIngestionFaultPolicy(IFailedAuditStorage failedAuditStorage, LoggingSettings settings, Func<string, Exception, Task> onCriticalError, IngestionMetrics metrics)
20+
public AuditIngestionFaultPolicy(
21+
IFailedAuditStorage failedAuditStorage,
22+
LoggingSettings settings,
23+
Func<string, Exception, Task> onCriticalError,
24+
IngestionMetrics metrics,
25+
ILogger logger)
2126
{
2227
failureCircuitBreaker = new ImportFailureCircuitBreaker(onCriticalError);
2328
this.failedAuditStorage = failedAuditStorage;
2429
this.metrics = metrics;
30+
this.logger = logger;
2531

2632
if (!AppEnvironment.RunningInContainer)
2733
{
@@ -75,20 +81,20 @@ async Task StoreFailedMessageDocument(ErrorContext errorContext, CancellationTok
7581

7682
async Task DoLogging(Exception exception, FailedAuditImport failure, CancellationToken cancellationToken)
7783
{
78-
log.Error("Failed importing error message", exception);
84+
logger.LogError(exception, "Failed importing error message");
7985

8086
// Write to storage
8187
await failedAuditStorage.SaveFailedAuditImport(failure);
8288

8389
if (!AppEnvironment.RunningInContainer)
8490
{
8591
// Write to Log Path
86-
var filePath = Path.Combine(logPath, failure.Id + ".txt");
92+
var filePath = Path.Combine(logPath, $"{failure.Id}.txt");
8793
await File.WriteAllTextAsync(filePath, failure.ExceptionInfo, cancellationToken);
8894

8995
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
9096
{
91-
WriteToEventLog("A message import has failed. A log file has been written to " + filePath);
97+
WriteToEventLog($"A message import has failed. A log file has been written to {filePath}");
9298
}
9399
}
94100
}
@@ -107,5 +113,5 @@ void WriteToEventLog(string message)
107113
readonly string logPath;
108114
readonly ImportFailureCircuitBreaker failureCircuitBreaker;
109115

110-
static readonly ILog log = LogManager.GetLogger<AuditIngestionFaultPolicy>();
116+
readonly ILogger logger;
111117
}

src/ServiceControl.Audit/Auditing/AuditIngestor.cs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@
66
using System.Threading;
77
using System.Threading.Tasks;
88
using Infrastructure.Settings;
9+
using Microsoft.Extensions.Logging;
910
using Monitoring;
1011
using NServiceBus;
11-
using NServiceBus.Logging;
1212
using NServiceBus.Routing;
1313
using NServiceBus.Transport;
1414
using Persistence.UnitOfWork;
@@ -25,12 +25,13 @@ public AuditIngestor(
2525
IEnumerable<IEnrichImportedAuditMessages> auditEnrichers, // allows extending message enrichers with custom enrichers registered in the DI container
2626
IMessageSession messageSession,
2727
Lazy<IMessageDispatcher> messageDispatcher,
28-
ITransportCustomization transportCustomization
28+
ITransportCustomization transportCustomization,
29+
ILogger<AuditIngestor> logger
2930
)
3031
{
3132
this.settings = settings;
3233
this.messageDispatcher = messageDispatcher;
33-
34+
this.logger = logger;
3435
var enrichers = new IEnrichImportedAuditMessages[] { new MessageTypeEnricher(), new EnrichWithTrackingIds(), new ProcessingStatisticsEnricher(), new DetectNewEndpointsFromAuditImportsEnricher(endpointInstanceMonitoring), new DetectSuccessfulRetriesEnricher(), new SagaRelationshipsEnricher() }.Concat(auditEnrichers).ToArray();
3536

3637
logQueueAddress = transportCustomization.ToTransportQualifiedQueueName(settings.AuditLogQueue);
@@ -39,7 +40,8 @@ ITransportCustomization transportCustomization
3940
unitOfWorkFactory,
4041
enrichers,
4142
messageSession,
42-
messageDispatcher
43+
messageDispatcher,
44+
logger
4345
);
4446
}
4547

@@ -61,7 +63,7 @@ public async Task Ingest(List<MessageContext> contexts, CancellationToken cancel
6163
}
6264
catch (Exception e)
6365
{
64-
Log.Warn("Forwarding messages failed", e);
66+
logger.LogWarning(e, "Forwarding messages failed");
6567

6668
// making sure to rethrow so that all messages get marked as failed
6769
throw;
@@ -129,6 +131,6 @@ public async Task VerifyCanReachForwardingAddress(CancellationToken cancellation
129131
readonly Lazy<IMessageDispatcher> messageDispatcher;
130132
readonly string logQueueAddress;
131133

132-
static readonly ILog Log = LogManager.GetLogger<AuditIngestor>();
134+
readonly ILogger logger;
133135
}
134136
}

0 commit comments

Comments
 (0)