Skip to content

Commit ff70494

Browse files
committed
simplify logging using with logger scopes
1 parent 5f440b0 commit ff70494

File tree

6 files changed

+40
-48
lines changed

6 files changed

+40
-48
lines changed

examples/Smdn.Net.MuninNode.Hosting/getting-started/Program.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,10 @@ static async Task Main(string[] args)
7878
)
7979
// Add other services.
8080
.AddLogging(builder => builder
81-
.AddSimpleConsole(static options => options.SingleLine = true)
81+
.AddSimpleConsole(static options => {
82+
options.SingleLine = true;
83+
options.IncludeScopes = true;
84+
})
8285
.AddFilter(static level => LogLevel.Trace <= level)
8386
);
8487

examples/Smdn.Net.MuninNode/getting-started/Program.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,10 @@ static async Task Main()
7272
)
7373
// Add other services.
7474
.AddLogging(builder => builder
75-
.AddSimpleConsole(static options => options.SingleLine = true)
75+
.AddSimpleConsole(static options => {
76+
options.SingleLine = true;
77+
options.IncludeScopes = true;
78+
})
7679
.AddFilter(static level => LogLevel.Trace <= level)
7780
);
7881

examples/Smdn.Net.MuninNode/local-node-uptime/Program.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,10 @@
5050

5151
services.AddLogging(
5252
builder => builder
53-
.AddSimpleConsole(static options => options.SingleLine = true)
53+
.AddSimpleConsole(static options => {
54+
options.SingleLine = true;
55+
options.IncludeScopes = true;
56+
})
5457
.AddFilter(static level => LogLevel.Trace <= level)
5558
);
5659

examples/Smdn.Net.MuninNode/multiple-fields/Program.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,10 @@
4040

4141
services.AddLogging(
4242
builder => builder
43-
.AddSimpleConsole(static options => options.SingleLine = true)
43+
.AddSimpleConsole(static options => {
44+
options.SingleLine = true;
45+
options.IncludeScopes = true;
46+
})
4447
.AddFilter(static level => LogLevel.Trace <= level)
4548
);
4649

src/Smdn.Net.MuninNode/Smdn.Net.MuninNode.Transport/MuninNodeClient.cs

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,8 @@ public async ValueTask<int> ReceiveAsync(IBufferWriter<byte> buffer, Cancellatio
7777
if (client is null)
7878
throw new ObjectDisposedException(GetType().FullName);
7979

80-
// holds a reference to the endpoint before the client being disposed
81-
var remoteEndPoint = client.RemoteEndPoint;
80+
// begin logger scope with this client's endpoint
81+
using var scope = logger?.BeginScope(client.RemoteEndPoint);
8282

8383
const int ReceiveChunkSize = 256;
8484
var totalByteCount = 0;
@@ -111,19 +111,15 @@ ex.SocketErrorCode is
111111
SocketError.ConnectionReset // ECONNRESET (104)
112112
) {
113113
logger?.LogDebug(
114-
"[{RemoteEndPoint}] expected socket exception ({NumericSocketErrorCode} {SocketErrorCode})",
115-
remoteEndPoint,
114+
"expected socket exception ({NumericSocketErrorCode} {SocketErrorCode})",
116115
(int)ex.SocketErrorCode,
117116
ex.SocketErrorCode
118117
);
119118

120119
break; // expected exception
121120
}
122121
catch (ObjectDisposedException) {
123-
logger?.LogDebug(
124-
"[{RemoteEndPoint}] socket has been disposed",
125-
remoteEndPoint
126-
);
122+
logger?.LogDebug("socket has been disposed");
127123

128124
break; // expected exception
129125
}

src/Smdn.Net.MuninNode/Smdn.Net.MuninNode/NodeBase.cs

Lines changed: 20 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -293,8 +293,8 @@ public async ValueTask AcceptSingleSessionAsync(
293293
cancellationToken: cancellationToken
294294
).ConfigureAwait(false);
295295

296-
// holds a reference to the endpoint before the client being disposed
297-
var remoteEndPoint = client.EndPoint;
296+
// begin logger scope with this client's endpoint
297+
using var scope = Logger?.BeginScope(client.EndPoint);
298298

299299
try {
300300
cancellationToken.ThrowIfCancellationRequested();
@@ -310,7 +310,7 @@ await ProcessSessionAsync(
310310
finally {
311311
await client.DisposeAsync().ConfigureAwait(false);
312312

313-
Logger?.LogInformation("[{RemoteEndPoint}] connection closed", remoteEndPoint);
313+
Logger?.LogInformation("connection closed");
314314
}
315315

316316
bool CanAccept(IMuninNodeClient client)
@@ -326,7 +326,7 @@ bool CanAccept(IMuninNodeClient client)
326326
}
327327

328328
if (accessRule is not null && !accessRule.IsAcceptable(remoteIPEndPoint)) {
329-
Logger?.LogWarning("access refused: {RemoteEndPoint}", remoteIPEndPoint);
329+
Logger?.LogWarning("access refused");
330330

331331
return false;
332332
}
@@ -342,11 +342,9 @@ CancellationToken cancellationToken
342342
{
343343
cancellationToken.ThrowIfCancellationRequested();
344344

345-
// holds a reference to the endpoint before the client being disposed
346-
var remoteEndPoint = client.EndPoint;
347-
var sessionId = GenerateSessionId(listener!.EndPoint, remoteEndPoint);
345+
var sessionId = GenerateSessionId(listener!.EndPoint, client.EndPoint);
348346

349-
Logger?.LogDebug("[{RemoteEndPoint}] sending banner", remoteEndPoint);
347+
Logger?.LogDebug("sending banner");
350348

351349
try {
352350
await SendResponseAsync(
@@ -356,19 +354,15 @@ await SendResponseAsync(
356354
).ConfigureAwait(false);
357355
}
358356
catch (MuninNodeClientDisconnectedException) {
359-
Logger?.LogWarning(
360-
"[{RemoteEndPoint}] client closed session while sending banner",
361-
remoteEndPoint
362-
);
357+
Logger?.LogWarning("client closed session while sending banner");
363358

364359
return;
365360
}
366361
#pragma warning disable CA1031
367362
catch (Exception ex) {
368363
Logger?.LogCritical(
369364
ex,
370-
"[{RemoteEndPoint}] unexpected exception occured while sending banner",
371-
remoteEndPoint
365+
"unexpected exception occured while sending banner"
372366
);
373367

374368
return;
@@ -377,7 +371,10 @@ await SendResponseAsync(
377371

378372
cancellationToken.ThrowIfCancellationRequested();
379373

380-
Logger?.LogInformation("[{RemoteEndPoint}] session started; ID={SessionId}", remoteEndPoint, sessionId);
374+
// begin logger scope with this session id
375+
using var scope = Logger?.BeginScope(sessionId);
376+
377+
Logger?.LogInformation("session started");
381378

382379
try {
383380
if (PluginProvider.SessionCallback is not null)
@@ -392,11 +389,11 @@ await SendResponseAsync(
392389
var pipe = new Pipe();
393390

394391
await Task.WhenAll(
395-
ReceiveCommandAsync(client, remoteEndPoint, pipe.Writer, cancellationToken),
396-
ProcessCommandAsync(client, remoteEndPoint, pipe.Reader, cancellationToken)
392+
ReceiveCommandAsync(client, pipe.Writer, cancellationToken),
393+
ProcessCommandAsync(client, pipe.Reader, cancellationToken)
397394
).ConfigureAwait(false);
398395

399-
Logger?.LogInformation("[{RemoteEndPoint}] session closed; ID={SessionId}", remoteEndPoint, sessionId);
396+
Logger?.LogInformation("session closed");
400397
}
401398
finally {
402399
foreach (var plugin in PluginProvider.Plugins) {
@@ -436,7 +433,6 @@ private static string GenerateSessionId(EndPoint? localEndPoint, EndPoint? remot
436433

437434
private async Task ReceiveCommandAsync(
438435
IMuninNodeClient client,
439-
EndPoint? remoteEndPoint,
440436
PipeWriter writer,
441437
CancellationToken cancellationToken
442438
)
@@ -451,18 +447,14 @@ CancellationToken cancellationToken
451447
break;
452448
}
453449
catch (OperationCanceledException) {
454-
Logger?.LogInformation(
455-
"[{RemoteEndPoint}] operation canceled",
456-
remoteEndPoint
457-
);
450+
Logger?.LogInformation("operation canceled");
458451
throw;
459452
}
460453
#pragma warning disable CA1031
461454
catch (Exception ex) {
462455
Logger?.LogError(
463456
ex,
464-
"[{RemoteEndPoint}] unexpected exception while receiving",
465-
remoteEndPoint
457+
"unexpected exception while receiving"
466458
);
467459
break; // swallow
468460
}
@@ -481,7 +473,6 @@ CancellationToken cancellationToken
481473

482474
private async Task ProcessCommandAsync(
483475
IMuninNodeClient client,
484-
EndPoint? remoteEndPoint,
485476
PipeReader reader,
486477
CancellationToken cancellationToken
487478
)
@@ -504,25 +495,18 @@ await RespondToCommandAsync(
504495
}
505496
}
506497
catch (MuninNodeClientDisconnectedException) {
507-
Logger?.LogInformation(
508-
"[{RemoteEndPoint}] client disconnected",
509-
remoteEndPoint
510-
);
498+
Logger?.LogInformation("client disconnected");
511499
break; // expected exception
512500
}
513501
catch (OperationCanceledException) {
514-
Logger?.LogInformation(
515-
"[{RemoteEndPoint}] operation canceled",
516-
remoteEndPoint
517-
);
502+
Logger?.LogInformation("operation canceled");
518503
throw;
519504
}
520505
#pragma warning disable CA1031
521506
catch (Exception ex) {
522507
Logger?.LogCritical(
523508
ex,
524-
"[{RemoteEndPoint}] unexpected exception while processing command",
525-
remoteEndPoint
509+
"unexpected exception while processing command"
526510
);
527511

528512
await client.DisconnectAsync(cancellationToken).ConfigureAwait(false);

0 commit comments

Comments
 (0)