-
Notifications
You must be signed in to change notification settings - Fork 1
/
AvaloniaNLogSink.cs
57 lines (50 loc) · 1.72 KB
/
AvaloniaNLogSink.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
50
51
52
53
54
55
56
57
using System;
using Avalonia;
using Avalonia.Logging;
using NLog;
namespace SharpFM;
/// <summary>
/// Avalonia Log Sink that writes to NLog Loggers.
/// </summary>
public class AvaloniaNLogSink : ILogSink
{
/// <summary>
/// AvaloniaNLogSink is always enabled.
/// </summary>
public bool IsEnabled(LogEventLevel level, string area) => true;
public void Log(LogEventLevel level, string area, object? source, string messageTemplate)
{
Log(level, area, source, messageTemplate, Array.Empty<object?>());
}
public void Log(LogEventLevel level, string area, object? source, string messageTemplate, params object?[] propertyValues)
{
ILogger? logger = source is not null ? LogManager.GetLogger(source.GetType().ToString())
: LogManager.GetLogger(typeof(AvaloniaNLogSink).ToString());
logger.Log(LogLevelToNLogLevel(level), $"{area}: {messageTemplate}", propertyValues);
}
private static LogLevel LogLevelToNLogLevel(LogEventLevel level)
{
return level switch
{
LogEventLevel.Verbose => LogLevel.Trace,
LogEventLevel.Debug => LogLevel.Debug,
LogEventLevel.Information => LogLevel.Info,
LogEventLevel.Warning => LogLevel.Warn,
LogEventLevel.Error => LogLevel.Error,
LogEventLevel.Fatal => LogLevel.Fatal,
_ => LogLevel.Trace,
};
}
}
public static class NLogSinkExtensions
{
/// <summary>
/// Creates an instance of the AvaloniaNLogSink and assigns it to the global sink.
/// </summary>
public static AppBuilder LogToNLog(
this AppBuilder builder)
{
Avalonia.Logging.Logger.Sink = new AvaloniaNLogSink();
return builder;
}
}