-
Notifications
You must be signed in to change notification settings - Fork 214
/
Copy pathScopedLogger.cs
49 lines (38 loc) · 1.4 KB
/
ScopedLogger.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace Elastic.Apm.Logging;
internal class ScopedLogger : IApmLogger
{
public ScopedLogger(IApmLogger logger, string scope) => (Logger, Scope) = (logger, scope);
internal ConditionalWeakTable<string, LogValuesFormatter> Formatters { get; } = new();
public IApmLogger Logger { get; }
#if !NET8_0_OR_GREATER
private readonly object _lock = new();
#endif
public string Scope { get; }
public bool IsEnabled(LogLevel level) => Logger.IsEnabled(level);
internal LogValuesFormatter GetOrAddFormatter(string message, IReadOnlyCollection<object> args)
{
if (Formatters.TryGetValue(message, out var formatter))
return formatter;
formatter = new LogValuesFormatter($"{{{{{{Scope}}}}}} {message}", args, Scope);
#if NET8_0_OR_GREATER
Formatters.AddOrUpdate(message, formatter);
return formatter;
#else
lock (_lock)
{
if (Formatters.TryGetValue(message, out var f))
return f;
Formatters.Add(message, formatter);
return formatter;
}
#endif
}
void IApmLogger.Log<TState>(LogLevel level, TState state, Exception e, Func<TState, Exception, string> formatter) =>
Logger.Log(level, state, e, formatter);
}