Skip to content

Commit d9caf6e

Browse files
authored
feat: introduce EntityLoggingScope to support scopes as key-value pairs inside custom properties of application insights (#893)
1 parent 9b0fe13 commit d9caf6e

File tree

2 files changed

+45
-11
lines changed

2 files changed

+45
-11
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
using System.Collections;
2+
3+
using k8s;
4+
using k8s.Models;
5+
6+
namespace KubeOps.Operator.Logging;
7+
8+
#pragma warning disable CA1710
9+
internal sealed record EntityLoggingScope : IReadOnlyCollection<KeyValuePair<string, object>>
10+
#pragma warning restore CA1710
11+
{
12+
private EntityLoggingScope(IReadOnlyDictionary<string, object> state)
13+
{
14+
Values = state;
15+
}
16+
17+
public int Count => Values.Count;
18+
19+
private string? CachedFormattedString { get; set; }
20+
21+
private IReadOnlyDictionary<string, object> Values { get; }
22+
23+
public static EntityLoggingScope CreateFor<TEntity>(WatchEventType eventType, TEntity entity)
24+
where TEntity : IKubernetesObject<V1ObjectMeta>
25+
=> new(
26+
new Dictionary<string, object>
27+
{
28+
{ "EventType", eventType },
29+
{ nameof(entity.Kind), entity.Kind },
30+
{ "Namespace", entity.Namespace() },
31+
{ "Name", entity.Name() },
32+
{ "ResourceVersion", entity.ResourceVersion() },
33+
});
34+
35+
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
36+
=> Values.GetEnumerator();
37+
38+
public override string ToString()
39+
=> CachedFormattedString ??= $"{{ {string.Join(", ", Values.Select(kvp => $"{kvp.Key} = {kvp.Value}"))} }}";
40+
41+
IEnumerator IEnumerable.GetEnumerator()
42+
=> GetEnumerator();
43+
}

src/KubeOps.Operator/Watcher/ResourceWatcher{TEntity}.cs

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
using KubeOps.Abstractions.Entities;
1212
using KubeOps.Abstractions.Finalizer;
1313
using KubeOps.KubernetesClient;
14+
using KubeOps.Operator.Logging;
1415
using KubeOps.Operator.Queue;
1516

1617
using Microsoft.Extensions.DependencyInjection;
@@ -200,17 +201,7 @@ private async Task WatchClientEventsAsync(CancellationToken stoppingToken)
200201
cancellationToken: stoppingToken))
201202
{
202203
#pragma warning disable SA1312
203-
using var _ = logger.BeginScope(new
204-
#pragma warning restore SA1312
205-
{
206-
EventType = type,
207-
208-
// ReSharper disable once RedundantAnonymousTypePropertyName
209-
Kind = entity.Kind,
210-
Namespace = entity.Namespace(),
211-
Name = entity.Name(),
212-
ResourceVersion = entity.ResourceVersion(),
213-
});
204+
using var _ = logger.BeginScope(EntityLoggingScope.CreateFor(type, entity));
214205
logger.LogInformation(
215206
"""Received watch event "{EventType}" for "{Kind}/{Name}", last observed resource version: {ResourceVersion}.""",
216207
type,

0 commit comments

Comments
 (0)