Skip to content

Commit 5d50cbf

Browse files
Work in progress
1 parent a9007b4 commit 5d50cbf

File tree

18 files changed

+72
-52
lines changed

18 files changed

+72
-52
lines changed

src/Directory.Packages.props

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
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.Abstractions" Version="8.0.3" />
2728
<PackageVersion Include="Microsoft.Extensions.TimeProvider.Testing" Version="8.10.0" />
2829
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
2930
<PackageVersion Include="Microsoft-WindowsAPICodePack-Shell" Version="1.1.5" />
@@ -63,6 +64,7 @@
6364
<PackageVersion Include="PublicApiGenerator" Version="11.4.6" />
6465
<PackageVersion Include="RavenDB.Embedded" Version="6.2.5" />
6566
<PackageVersion Include="ReactiveUI.WPF" Version="20.1.63" />
67+
<PackageVersion Include="Seq.Extensions.Logging" Version="8.0.0" />
6668
<PackageVersion Include="ServiceControl.Contracts" Version="5.0.0" />
6769
<PackageVersion Include="System.Configuration.ConfigurationManager" Version="8.0.1" />
6870
<PackageVersion Include="System.Diagnostics.PerformanceCounter" Version="8.0.1" />
@@ -91,4 +93,4 @@
9193
<GlobalPackageReference Include="Microsoft.Build.CopyOnWrite" Version="1.0.334" />
9294
<GlobalPackageReference Include="Particular.Packaging" Version="4.2.2" />
9395
</ItemGroup>
94-
</Project>
96+
</Project>

src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs

Lines changed: 1 addition & 1 deletion
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;

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

Lines changed: 2 additions & 1 deletion
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,7 @@ 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);
4748

4849
settings = new Settings(transportToUse.TypeName, persistenceToUse.PersistenceType, loggingSettings)
4950
{

src/ServiceControl.Audit.Persistence.RavenDB/CustomChecks/CheckFreeDiskSpace.cs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
using Microsoft.Extensions.Logging;
99
using NServiceBus.CustomChecks;
1010
using RavenDB;
11-
using ServiceControl.Infrastructure;
1211

1312
class CheckFreeDiskSpace(DatabaseConfiguration databaseConfiguration, ILogger<CheckFreeDiskSpace> logger) : CustomCheck("ServiceControl.Audit database", "Storage space", TimeSpan.FromMinutes(5))
1413
{
@@ -45,7 +44,7 @@ public override Task<CheckResult> PerformCheck(CancellationToken cancellationTok
4544
: CheckResult.Failed($"{percentRemaining:P0} disk space remaining on data drive '{dataDriveInfo.VolumeLabel} ({dataDriveInfo.RootDirectory})' on '{Environment.MachineName}'.");
4645
}
4746

48-
public static int Parse(IDictionary<string, string> settings)
47+
public static int Parse(IDictionary<string, string> settings, ILogger logger)
4948
{
5049
if (!settings.TryGetValue(RavenPersistenceConfiguration.DataSpaceRemainingThresholdKey, out var thresholdValue))
5150
{
@@ -54,19 +53,19 @@ public static int Parse(IDictionary<string, string> settings)
5453

5554
if (!int.TryParse(thresholdValue, out var threshold))
5655
{
57-
Logger.LogCritical("{RavenPersistenceConfigurationDataSpaceRemainingThresholdKey} must be an integer.", RavenPersistenceConfiguration.DataSpaceRemainingThresholdKey);
56+
logger.LogCritical("{RavenPersistenceConfigurationDataSpaceRemainingThresholdKey} must be an integer.", RavenPersistenceConfiguration.DataSpaceRemainingThresholdKey);
5857
throw new Exception($"{RavenPersistenceConfiguration.DataSpaceRemainingThresholdKey} must be an integer.");
5958
}
6059

6160
if (threshold < 0)
6261
{
63-
Logger.LogCritical("{RavenPersistenceConfigurationDataSpaceRemainingThresholdKey} is invalid, minimum value is 0.", RavenPersistenceConfiguration.DataSpaceRemainingThresholdKey);
62+
logger.LogCritical("{RavenPersistenceConfigurationDataSpaceRemainingThresholdKey} is invalid, minimum value is 0.", RavenPersistenceConfiguration.DataSpaceRemainingThresholdKey);
6463
throw new Exception($"{RavenPersistenceConfiguration.DataSpaceRemainingThresholdKey} is invalid, minimum value is 0.");
6564
}
6665

6766
if (threshold > 100)
6867
{
69-
Logger.LogCritical("{RavenPersistenceConfigurationDataSpaceRemainingThresholdKey} is invalid, maximum value is 100.", RavenPersistenceConfiguration.DataSpaceRemainingThresholdKey);
68+
logger.LogCritical("{RavenPersistenceConfigurationDataSpaceRemainingThresholdKey} is invalid, maximum value is 100.", RavenPersistenceConfiguration.DataSpaceRemainingThresholdKey);
7069
throw new Exception($"{RavenPersistenceConfiguration.DataSpaceRemainingThresholdKey} is invalid, maximum value is 100.");
7170
}
7271

@@ -75,7 +74,6 @@ public static int Parse(IDictionary<string, string> settings)
7574

7675
readonly string dataPathRoot = Path.GetPathRoot(databaseConfiguration.ServerConfiguration.DbPath);
7776
readonly decimal percentageThreshold = databaseConfiguration.DataSpaceRemainingThreshold / 100m;
78-
static readonly ILogger<CheckFreeDiskSpace> Logger = LoggerUtil.CreateStaticLogger<CheckFreeDiskSpace>();
7977
public const int DataSpaceRemainingThresholdDefault = 20;
8078
}
8179
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ internal static DatabaseConfiguration GetDatabaseConfiguration(PersistenceSettin
114114
serverConfiguration = new ServerConfiguration(dbPath, serverUrl, logPath, logsMode);
115115
}
116116

117-
var dataSpaceRemainingThreshold = CheckFreeDiskSpace.Parse(settings.PersisterSpecificSettings);
117+
var dataSpaceRemainingThreshold = CheckFreeDiskSpace.Parse(settings.PersisterSpecificSettings, Logger);
118118
var minimumStorageLeftRequiredForIngestion = CheckMinimumStorageRequiredForIngestion.Parse(settings.PersisterSpecificSettings);
119119

120120
var expirationProcessTimerInSeconds = GetExpirationProcessTimerInSeconds(settings);

src/ServiceControl.Audit/HostApplicationBuilderExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public static void AddServiceControlAudit(this IHostApplicationBuilder builder,
4141

4242
builder.Logging.ClearProviders();
4343
builder.Logging.AddNLog();
44-
builder.Logging.SetMinimumLevel(settings.LoggingSettings.ToHostLogLevel());
44+
builder.Logging.SetMinimumLevel(settings.LoggingSettings.LogLevel);
4545

4646
var services = builder.Services;
4747
var transportSettings = settings.ToTransportSettings();

src/ServiceControl.Audit/Infrastructure/WebApi/RootController.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public OkObjectResult Config()
5151
Logging = new
5252
{
5353
settings.LoggingSettings.LogPath,
54-
LoggingLevel = settings.LoggingSettings.LogLevel.Name
54+
LoggingLevel = settings.LoggingSettings.LogLevel
5555
}
5656
},
5757
DataRetention = new

src/ServiceControl.Infrastructure/LoggerUtil.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,16 @@ public static class LoggerUtil
99
public static void BuildLogger(this ILoggingBuilder loggingBuilder, LogLevel level)
1010
{
1111
loggingBuilder.AddNLog();
12+
loggingBuilder.AddSeq();
1213
loggingBuilder.SetMinimumLevel(level);
1314
}
1415

1516
public static ILogger<T> CreateStaticLogger<T>(LogLevel level = LogLevel.Information)
1617
{
1718
var factory = LoggerFactory.Create(configure => configure.BuildLogger(level));
18-
return factory.CreateLogger<T>();
19+
var logger = factory.CreateLogger<T>();
20+
logger.LogError("JTD: This is a test log message.");
21+
return logger;
1922
}
2023

2124
public static ILogger CreateStaticLogger(Type type, LogLevel level = LogLevel.Information)

src/ServiceControl.Infrastructure/LoggingConfigurator.cs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,11 +60,15 @@ public static void ConfigureLogging(LoggingSettings loggingSettings)
6060
nlogConfig.LoggingRules.Add(aspNetCoreRule);
6161
nlogConfig.LoggingRules.Add(httpClientRule);
6262

63-
nlogConfig.LoggingRules.Add(new LoggingRule("*", loggingSettings.LogLevel, consoleTarget));
63+
// HACK: Fix LogLevel to Info for testing purposes only.
64+
// nlogConfig.LoggingRules.Add(new LoggingRule("*", loggingSettings.LogLevel, consoleTarget));
65+
nlogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget));
6466

6567
if (!AppEnvironment.RunningInContainer)
6668
{
67-
nlogConfig.LoggingRules.Add(new LoggingRule("*", loggingSettings.LogLevel, fileTarget));
69+
// HACK: Fix LogLevel to Info for testing purposes only.
70+
//nlogConfig.LoggingRules.Add(new LoggingRule("*", loggingSettings.LogLevel, fileTarget));
71+
nlogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget));
6872
}
6973

7074
NLog.LogManager.Configuration = nlogConfig;
@@ -74,7 +78,7 @@ public static void ConfigureLogging(LoggingSettings loggingSettings)
7478
var logger = LogManager.GetLogger("LoggingConfiguration");
7579
var logEventInfo = new LogEventInfo { TimeStamp = DateTime.UtcNow };
7680
var loggingTo = AppEnvironment.RunningInContainer ? "console" : fileTarget.FileName.Render(logEventInfo);
77-
logger.InfoFormat("Logging to {0} with LogLevel '{1}'", loggingTo, loggingSettings.LogLevel.Name);
81+
logger.InfoFormat("Logging to {0} with LogLevel '{1}'", loggingTo, LogLevel.Info.Name);
7882
}
7983

8084
const long megaByte = 1024 * 1024;
Lines changed: 31 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,60 @@
11
namespace ServiceControl.Infrastructure;
22

33
using System;
4+
using System.Collections.Generic;
45
using System.IO;
5-
using NLog;
6-
using NLog.Common;
6+
using Microsoft.Extensions.Logging;
77
using ServiceControl.Configuration;
88

9-
public class LoggingSettings(SettingsRootNamespace rootNamespace, LogLevel defaultLevel = null, string logPath = null)
9+
public class LoggingSettings(SettingsRootNamespace rootNamespace, LogLevel defaultLevel = LogLevel.Information, string logPath = null)
1010
{
1111
public LogLevel LogLevel { get; } = InitializeLogLevel(rootNamespace, defaultLevel);
1212

13-
public string LogPath { get; } = SettingsReader.Read(rootNamespace, "LogPath", Environment.ExpandEnvironmentVariables(logPath ?? DefaultLogLocation()));
13+
public string LogPath { get; } = SettingsReader.Read(rootNamespace, logPathKey, Environment.ExpandEnvironmentVariables(logPath ?? DefaultLogLocation()));
1414

1515
static LogLevel InitializeLogLevel(SettingsRootNamespace rootNamespace, LogLevel defaultLevel)
1616
{
17-
defaultLevel ??= LogLevel.Info;
18-
1917
var levelText = SettingsReader.Read<string>(rootNamespace, logLevelKey);
2018

2119
if (string.IsNullOrWhiteSpace(levelText))
2220
{
2321
return defaultLevel;
2422
}
2523

26-
try
27-
{
28-
return LogLevel.FromString(levelText);
29-
}
30-
catch
31-
{
32-
InternalLogger.Warn($"Failed to parse {logLevelKey} setting. Defaulting to {defaultLevel.Name}.");
33-
return defaultLevel;
34-
}
24+
return ParseLogLevel(levelText, defaultLevel);
3525
}
3626

3727
// SC installer always populates LogPath in app.config on installation/change/upgrade so this will only be used when
3828
// debugging or if the entry is removed manually. In those circumstances default to the folder containing the exe
3929
static string DefaultLogLocation() => Path.Combine(AppContext.BaseDirectory, ".logs");
4030

41-
public Microsoft.Extensions.Logging.LogLevel ToHostLogLevel() => LogLevel switch
31+
// This is not a complete mapping of NLog levels, just the ones that are different.
32+
static readonly Dictionary<string, LogLevel> NLogAliases =
33+
new(StringComparer.OrdinalIgnoreCase)
34+
{
35+
["info"] = LogLevel.Information,
36+
["warn"] = LogLevel.Warning,
37+
["fatal"] = LogLevel.Critical,
38+
["off"] = LogLevel.None
39+
};
40+
41+
static LogLevel ParseLogLevel(string value, LogLevel defaultLevel)
4242
{
43-
_ when LogLevel == LogLevel.Trace => Microsoft.Extensions.Logging.LogLevel.Trace,
44-
_ when LogLevel == LogLevel.Debug => Microsoft.Extensions.Logging.LogLevel.Debug,
45-
_ when LogLevel == LogLevel.Info => Microsoft.Extensions.Logging.LogLevel.Information,
46-
_ when LogLevel == LogLevel.Warn => Microsoft.Extensions.Logging.LogLevel.Warning,
47-
_ when LogLevel == LogLevel.Error => Microsoft.Extensions.Logging.LogLevel.Error,
48-
_ when LogLevel == LogLevel.Fatal => Microsoft.Extensions.Logging.LogLevel.Critical,
49-
_ => Microsoft.Extensions.Logging.LogLevel.None
50-
};
43+
if (Enum.TryParse(value, ignoreCase: true, out LogLevel parsedLevel))
44+
{
45+
return parsedLevel;
46+
}
47+
48+
if (NLogAliases.TryGetValue(value.Trim(), out parsedLevel))
49+
{
50+
return parsedLevel;
51+
}
52+
53+
LoggerUtil.CreateStaticLogger<LoggingSettings>().LogWarning("Failed to parse {LogLevelKey} setting. Defaulting to {DefaultLevel}.", logLevelKey, defaultLevel);
54+
55+
return defaultLevel;
56+
}
5157

5258
const string logLevelKey = "LogLevel";
59+
const string logPathKey = "LogPath";
5360
}

0 commit comments

Comments
 (0)