Skip to content

Commit aeafb27

Browse files
committed
centralize log assignment
1 parent 9966763 commit aeafb27

File tree

8 files changed

+59
-74
lines changed

8 files changed

+59
-74
lines changed

.editorconfig

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,9 @@ csharp_style_namespace_declarations = file_scoped
213213
dotnet_analyzer_diagnostic.severity = warning
214214
dotnet_analyzer_diagnostic.category-Style.severity = warning
215215

216+
# can be made static
217+
dotnet_diagnostic.CA1822.severity = suggestion
218+
216219
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1848
217220
dotnet_diagnostic.CA1848.severity = suggestion
218221
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2201

src/tooling/docs-assembler/Cli/DeployCommands.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,6 @@ public async Task<int> Apply(
103103
/// <param name="redirectsFile">Path to the redirects mapping pre-generated by docs-assembler</param>
104104
/// <param name="ctx"></param>
105105
[Command("update-redirects")]
106-
[ConsoleAppFilter<StopwatchFilter>]
107-
[ConsoleAppFilter<CatchExceptionFilter>]
108106
public async Task<int> UpdateRedirects(
109107
string environment,
110108
string redirectsFile = ".artifacts/assembly/redirects.json",

src/tooling/docs-assembler/Cli/NavigationCommands.cs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,6 @@ private void AssignOutputLogger()
2929
/// <summary> Validates navigation.yml does not contain colliding path prefixes </summary>
3030
/// <param name="ctx"></param>
3131
[Command("validate")]
32-
[ConsoleAppFilter<StopwatchFilter>]
33-
[ConsoleAppFilter<CatchExceptionFilter>]
3432
public async Task<int> Validate(Cancel ctx = default)
3533
{
3634
AssignOutputLogger();
@@ -56,8 +54,6 @@ public async Task<int> Validate(Cancel ctx = default)
5654
/// <param name="file">Path to `links.json` defaults to '.artifacts/docs/html/links.json'</param>
5755
/// <param name="ctx"></param>
5856
[Command("validate-link-reference")]
59-
[ConsoleAppFilter<StopwatchFilter>]
60-
[ConsoleAppFilter<CatchExceptionFilter>]
6157
public async Task<int> ValidateLocalLinkReference([Argument] string? file = null, Cancel ctx = default)
6258
{
6359
AssignOutputLogger();

src/tooling/docs-assembler/Program.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
33
// See the LICENSE file in the project root for more information
44

5+
using System.Diagnostics.CodeAnalysis;
56
using Actions.Core.Services;
67
using ConsoleAppFramework;
78
using Documentation.Assembler.Cli;
89
using Elastic.Documentation.Diagnostics;
910
using Elastic.Documentation.Tooling;
1011
using Elastic.Documentation.Tooling.Filters;
1112
using Microsoft.Extensions.DependencyInjection;
13+
using Microsoft.Extensions.Logging;
1214

1315
await using var serviceProvider = DocumentationTooling.CreateServiceProvider(ref args, services => services
1416
.AddSingleton<DiagnosticsChannel>()
@@ -19,6 +21,7 @@
1921
ConsoleApp.ServiceProvider = serviceProvider;
2022

2123
var app = ConsoleApp.Create();
24+
app.UseFilter<ReplaceLogFilter>();
2225
app.UseFilter<StopwatchFilter>();
2326
app.UseFilter<CatchExceptionFilter>();
2427

@@ -35,3 +38,16 @@
3538
args = command.Split(' ');
3639

3740
await app.RunAsync(args);
41+
42+
internal sealed class ReplaceLogFilter(ConsoleAppFilter next, ILogger<Program> logger)
43+
: ConsoleAppFilter(next)
44+
{
45+
[SuppressMessage("Usage", "CA2254:Template should be a static expression")]
46+
public override Task InvokeAsync(ConsoleAppContext context, Cancel cancellationToken)
47+
{
48+
ConsoleApp.Log = msg => logger.LogInformation(msg);
49+
ConsoleApp.LogError = msg => logger.LogError(msg);
50+
51+
return Next.InvokeAsync(context, cancellationToken);
52+
}
53+
}

src/tooling/docs-builder/Cli/Commands.cs

Lines changed: 16 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
33
// See the LICENSE file in the project root for more information
44

5-
using System.Diagnostics.CodeAnalysis;
65
using System.IO.Abstractions;
76
using System.IO.Abstractions.TestingHelpers;
87
using Actions.Core.Services;
@@ -13,7 +12,6 @@
1312
using Elastic.Documentation.Configuration.Versions;
1413
using Elastic.Documentation.Refactor;
1514
using Elastic.Documentation.Tooling.Diagnostics.Console;
16-
using Elastic.Documentation.Tooling.Filters;
1715
using Elastic.Markdown;
1816
using Elastic.Markdown.Exporters;
1917
using Elastic.Markdown.IO;
@@ -22,16 +20,9 @@
2220

2321
namespace Documentation.Builder.Cli;
2422

25-
internal sealed class Commands(ILoggerFactory logger, ICoreService githubActionsService, IOptions<VersionsConfiguration> versionsConfigOption)
23+
internal sealed class Commands(ILoggerFactory logFactory, ICoreService githubActionsService, IOptions<VersionsConfiguration> versionsConfigOption)
2624
{
27-
private readonly ILogger<Program> _log = logger.CreateLogger<Program>();
28-
29-
[SuppressMessage("Usage", "CA2254:Template should be a static expression")]
30-
private void AssignOutputLogger()
31-
{
32-
ConsoleApp.Log = msg => _log.LogInformation(msg);
33-
ConsoleApp.LogError = msg => _log.LogError(msg);
34-
}
25+
private readonly ILogger<Program> _log = logFactory.CreateLogger<Program>();
3526

3627
/// <summary>
3728
/// Continuously serve a documentation folder at http://localhost:3000.
@@ -43,11 +34,9 @@ private void AssignOutputLogger()
4334
/// <param name="port">Port to serve the documentation.</param>
4435
/// <param name="ctx"></param>
4536
[Command("serve")]
46-
[ConsoleAppFilter<CheckForUpdatesFilter>]
4737
public async Task Serve(string? path = null, int port = 3000, Cancel ctx = default)
4838
{
49-
AssignOutputLogger();
50-
var host = new DocumentationWebHost(path, port, logger, new FileSystem(), new MockFileSystem(), versionsConfigOption.Value);
39+
var host = new DocumentationWebHost(path, port, logFactory, new FileSystem(), new MockFileSystem(), versionsConfigOption.Value);
5140
_log.LogInformation("Find your documentation at http://localhost:{Port}/{Path}", port,
5241
host.GeneratorState.Generator.DocumentationSet.FirstInterestingUrl.TrimStart('/')
5342
);
@@ -56,22 +45,20 @@ public async Task Serve(string? path = null, int port = 3000, Cancel ctx = defau
5645
}
5746

5847
/// <summary>
59-
/// Serve html files directly
48+
/// Serve HTML files directly
6049
/// </summary>
6150
/// <param name="port">Port to serve the documentation.</param>
6251
/// <param name="ctx"></param>
6352
[Command("serve-static")]
64-
[ConsoleAppFilter<CheckForUpdatesFilter>]
6553
public async Task ServeStatic(int port = 4000, Cancel ctx = default)
6654
{
67-
AssignOutputLogger();
6855
var host = new StaticWebHost(port);
6956
await host.RunAsync(ctx);
7057
await host.StopAsync(ctx);
7158
}
7259

7360
/// <summary>
74-
/// Converts a source markdown folder or file to an output folder
61+
/// Converts a source Markdown folder or file to an output folder
7562
/// <para>global options:</para>
7663
/// --log-level level
7764
/// </summary>
@@ -80,14 +67,11 @@ public async Task ServeStatic(int port = 4000, Cancel ctx = default)
8067
/// <param name="pathPrefix"> Specifies the path prefix for urls </param>
8168
/// <param name="force"> Force a full rebuild of the destination folder</param>
8269
/// <param name="strict"> Treat warnings as errors and fail the build on warnings</param>
83-
/// <param name="allowIndexing"> Allow indexing and following of html files</param>
70+
/// <param name="allowIndexing"> Allow indexing and following of HTML files</param>
8471
/// <param name="metadataOnly"> Only emit documentation metadata to output</param>
8572
/// <param name="canonicalBaseUrl"> The base URL for the canonical url tag</param>
8673
/// <param name="ctx"></param>
8774
[Command("generate")]
88-
[ConsoleAppFilter<StopwatchFilter>]
89-
[ConsoleAppFilter<CatchExceptionFilter>]
90-
[ConsoleAppFilter<CheckForUpdatesFilter>]
9175
public async Task<int> Generate(
9276
string? path = null,
9377
string? output = null,
@@ -100,10 +84,9 @@ public async Task<int> Generate(
10084
Cancel ctx = default
10185
)
10286
{
103-
AssignOutputLogger();
10487
pathPrefix ??= githubActionsService.GetInput("prefix");
10588
var fileSystem = new FileSystem();
106-
await using var collector = new ConsoleDiagnosticsCollector(logger, githubActionsService).StartAsync(ctx);
89+
await using var collector = new ConsoleDiagnosticsCollector(logFactory, githubActionsService).StartAsync(ctx);
10790

10891
var runningOnCi = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GITHUB_ACTIONS"));
10992
BuildContext context;
@@ -139,7 +122,7 @@ public async Task<int> Generate(
139122
var outputDirectory = !string.IsNullOrWhiteSpace(output)
140123
? fileSystem.DirectoryInfo.New(output)
141124
: fileSystem.DirectoryInfo.New(Path.Combine(Paths.WorkingDirectoryRoot.FullName, ".artifacts/docs/html"));
142-
// we temporarily do not error when pointed to a non documentation folder.
125+
// we temporarily do not error when pointed to a non-documentation folder.
143126
_ = fileSystem.Directory.CreateDirectory(outputDirectory.FullName);
144127

145128
ConsoleApp.Log($"Skipping build as we are running on a merge commit and the docs folder is out of date and has no docset.yml. {e.Message}");
@@ -152,7 +135,7 @@ public async Task<int> Generate(
152135
await githubActionsService.SetOutputAsync("skip", "false");
153136

154137
// always delete output folder on CI
155-
var set = new DocumentationSet(context, logger);
138+
var set = new DocumentationSet(context, logFactory);
156139
if (runningOnCi)
157140
set.ClearOutputDirectory();
158141

@@ -161,11 +144,11 @@ public async Task<int> Generate(
161144
metadataOnly ??= metaValue;
162145
var exporter = metadataOnly.HasValue && metadataOnly.Value ? new NoopDocumentationFileExporter() : null;
163146

164-
var generator = new DocumentationGenerator(set, logger, null, null, null, exporter);
147+
var generator = new DocumentationGenerator(set, logFactory, null, null, null, exporter);
165148
_ = await generator.GenerateAll(ctx);
166149

167150

168-
var openApiGenerator = new OpenApiGenerator(context, generator.MarkdownStringRenderer, logger);
151+
var openApiGenerator = new OpenApiGenerator(context, generator.MarkdownStringRenderer, logFactory);
169152
await openApiGenerator.Generate(ctx);
170153

171154
if (runningOnCi)
@@ -180,21 +163,18 @@ public async Task<int> Generate(
180163
}
181164

182165
/// <summary>
183-
/// Converts a source markdown folder or file to an output folder
166+
/// Converts a source Markdown folder or file to an output folder
184167
/// </summary>
185168
/// <param name="path"> -p, Defaults to the`{pwd}/docs` folder</param>
186169
/// <param name="output"> -o, Defaults to `.artifacts/html` </param>
187170
/// <param name="pathPrefix"> Specifies the path prefix for urls </param>
188171
/// <param name="force"> Force a full rebuild of the destination folder</param>
189172
/// <param name="strict"> Treat warnings as errors and fail the build on warnings</param>
190-
/// <param name="allowIndexing"> Allow indexing and following of html files</param>
173+
/// <param name="allowIndexing"> Allow indexing and following of HTML files</param>
191174
/// <param name="metadataOnly"> Only emit documentation metadata to output</param>
192175
/// <param name="canonicalBaseUrl"> The base URL for the canonical url tag</param>
193176
/// <param name="ctx"></param>
194177
[Command("")]
195-
[ConsoleAppFilter<StopwatchFilter>]
196-
[ConsoleAppFilter<CatchExceptionFilter>]
197-
[ConsoleAppFilter<CheckForUpdatesFilter>]
198178
public async Task<int> GenerateDefault(
199179
string? path = null,
200180
string? output = null,
@@ -218,9 +198,6 @@ public async Task<int> GenerateDefault(
218198
/// <param name="dryRun">Dry run the move operation</param>
219199
/// <param name="ctx"></param>
220200
[Command("mv")]
221-
[ConsoleAppFilter<StopwatchFilter>]
222-
[ConsoleAppFilter<CatchExceptionFilter>]
223-
[ConsoleAppFilter<CheckForUpdatesFilter>]
224201
public async Task<int> Move(
225202
[Argument] string source,
226203
[Argument] string target,
@@ -229,13 +206,12 @@ public async Task<int> Move(
229206
Cancel ctx = default
230207
)
231208
{
232-
AssignOutputLogger();
233209
var fileSystem = new FileSystem();
234-
await using var collector = new ConsoleDiagnosticsCollector(logger, null).StartAsync(ctx);
210+
await using var collector = new ConsoleDiagnosticsCollector(logFactory, null).StartAsync(ctx);
235211
var context = new BuildContext(collector, fileSystem, fileSystem, versionsConfigOption.Value, path, null);
236-
var set = new DocumentationSet(context, logger);
212+
var set = new DocumentationSet(context, logFactory);
237213

238-
var moveCommand = new Move(fileSystem, fileSystem, set, logger);
214+
var moveCommand = new Move(fileSystem, fileSystem, set, logFactory);
239215
var result = await moveCommand.Execute(source, target, dryRun ?? false, ctx);
240216
await collector.StopAsync(ctx);
241217
return result;

src/tooling/docs-builder/Cli/DiffCommands.cs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,8 @@ internal sealed class DiffCommands(ILoggerFactory logger, ICoreService githubAct
2626
/// <param name="ctx"></param>
2727
[SuppressMessage("Usage", "CA2254:Template should be a static expression")]
2828
[Command("validate")]
29-
[ConsoleAppFilter<StopwatchFilter>]
30-
[ConsoleAppFilter<CatchExceptionFilter>]
3129
public async Task<int> ValidateRedirects([Argument] string? path = null, Cancel ctx = default)
3230
{
33-
var log = logger.CreateLogger<Program>();
34-
ConsoleApp.Log = msg => log.LogInformation(msg);
35-
ConsoleApp.LogError = msg => log.LogError(msg);
36-
3731
path ??= "docs";
3832

3933
await using var collector = new ConsoleDiagnosticsCollector(logger, githubActionsService).StartAsync(ctx);

src/tooling/docs-builder/Cli/InboundLinkCommands.cs

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,21 +20,11 @@ internal sealed class InboundLinkCommands(ILoggerFactory logger, ICoreService gi
2020
private readonly LinkIndexLinkChecker _linkIndexLinkChecker = new(logger);
2121
private readonly ILogger<Program> _log = logger.CreateLogger<Program>();
2222

23-
[SuppressMessage("Usage", "CA2254:Template should be a static expression")]
24-
private void AssignOutputLogger()
25-
{
26-
ConsoleApp.Log = msg => _log.LogInformation(msg);
27-
ConsoleApp.LogError = msg => _log.LogError(msg);
28-
}
29-
3023
/// <summary> Validate all published cross_links in all published links.json files. </summary>
3124
/// <param name="ctx"></param>
3225
[Command("validate-all")]
33-
[ConsoleAppFilter<StopwatchFilter>]
34-
[ConsoleAppFilter<CatchExceptionFilter>]
3526
public async Task<int> ValidateAllInboundLinks(Cancel ctx = default)
3627
{
37-
AssignOutputLogger();
3828
await using var collector = new ConsoleDiagnosticsCollector(logger, githubActionsService).StartAsync(ctx);
3929
await _linkIndexLinkChecker.CheckAll(collector, ctx);
4030
await collector.StopAsync(ctx);
@@ -46,11 +36,8 @@ public async Task<int> ValidateAllInboundLinks(Cancel ctx = default)
4636
/// <param name="to">Outbound links 'to' repository form others</param>
4737
/// <param name="ctx"></param>
4838
[Command("validate")]
49-
[ConsoleAppFilter<StopwatchFilter>]
50-
[ConsoleAppFilter<CatchExceptionFilter>]
5139
public async Task<int> ValidateRepoInboundLinks(string? from = null, string? to = null, Cancel ctx = default)
5240
{
53-
AssignOutputLogger();
5441
var fs = new FileSystem();
5542
var root = fs.DirectoryInfo.New(Paths.WorkingDirectoryRoot.FullName);
5643
if (from == null && to == null)
@@ -72,11 +59,8 @@ public async Task<int> ValidateRepoInboundLinks(string? from = null, string? to
7259
/// <param name="path"> -p, Defaults to the `{pwd}` folder</param>
7360
/// <param name="ctx"></param>
7461
[Command("validate-link-reference")]
75-
[ConsoleAppFilter<StopwatchFilter>]
76-
[ConsoleAppFilter<CatchExceptionFilter>]
7762
public async Task<int> ValidateLocalLinkReference(string? file = null, string? path = null, Cancel ctx = default)
7863
{
79-
AssignOutputLogger();
8064
file ??= ".artifacts/docs/html/links.json";
8165
var fs = new FileSystem();
8266
var root = !string.IsNullOrEmpty(path) ? fs.DirectoryInfo.New(path) : fs.DirectoryInfo.New(Paths.WorkingDirectoryRoot.FullName);

src/tooling/docs-builder/Program.cs

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,39 @@
22
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
33
// See the LICENSE file in the project root for more information
44

5+
using System.Diagnostics.CodeAnalysis;
56
using ConsoleAppFramework;
67
using Documentation.Builder.Cli;
7-
using Elastic.Documentation.Diagnostics;
88
using Elastic.Documentation.Tooling;
9-
using Microsoft.Extensions.DependencyInjection;
9+
using Elastic.Documentation.Tooling.Filters;
10+
using Microsoft.Extensions.Logging;
1011

11-
await using var serviceProvider = DocumentationTooling.CreateServiceProvider(ref args, services => services
12-
.AddSingleton<DiagnosticsChannel>()
13-
.AddSingleton<DiagnosticsCollector>()
14-
);
12+
await using var serviceProvider = DocumentationTooling.CreateServiceProvider(ref args, _ => { });
1513
ConsoleApp.ServiceProvider = serviceProvider;
1614

1715
var app = ConsoleApp.Create();
16+
17+
app.UseFilter<ReplaceLogFilter>();
18+
app.UseFilter<StopwatchFilter>();
19+
app.UseFilter<CatchExceptionFilter>();
20+
app.UseFilter<CheckForUpdatesFilter>();
21+
1822
app.Add<Commands>();
1923
app.Add<InboundLinkCommands>("inbound-links");
2024
app.Add<DiffCommands>("diff");
2125

2226
await app.RunAsync(args).ConfigureAwait(false);
27+
28+
29+
internal sealed class ReplaceLogFilter(ConsoleAppFilter next, ILogger<Program> logger)
30+
: ConsoleAppFilter(next)
31+
{
32+
[SuppressMessage("Usage", "CA2254:Template should be a static expression")]
33+
public override Task InvokeAsync(ConsoleAppContext context, Cancel cancellationToken)
34+
{
35+
ConsoleApp.Log = msg => logger.LogInformation(msg);
36+
ConsoleApp.LogError = msg => logger.LogError(msg);
37+
38+
return Next.InvokeAsync(context, cancellationToken);
39+
}
40+
}

0 commit comments

Comments
 (0)