diff --git a/SharpFM.App/AvaloniaNLogSink.cs b/SharpFM.App/AvaloniaNLogSink.cs new file mode 100644 index 0000000..d394148 --- /dev/null +++ b/SharpFM.App/AvaloniaNLogSink.cs @@ -0,0 +1,57 @@ +using System; +using Avalonia; +using Avalonia.Logging; +using NLog; + +namespace SharpFM.App; + +/// +/// Avalonia Log Sink that writes to NLog Loggers. +/// +public class AvaloniaNLogSink : ILogSink +{ + /// + /// AvaloniaNLogSink is always enabled. + /// + 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()); + } + + 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 +{ + /// + /// Creates an instance of the AvaloniaNLogSink and assigns it to the global sink. + /// + public static AppBuilder LogToNLog( + this AppBuilder builder) + { + Avalonia.Logging.Logger.Sink = new AvaloniaNLogSink(); + return builder; + } +} \ No newline at end of file diff --git a/SharpFM.App/Program.cs b/SharpFM.App/Program.cs index e57d73d..8c3952a 100644 --- a/SharpFM.App/Program.cs +++ b/SharpFM.App/Program.cs @@ -9,13 +9,15 @@ class Program // SynchronizationContext-reliant code before AppMain is called: things aren't initialized // yet and stuff might break. [STAThread] - public static void Main(string[] args) => BuildAvaloniaApp() - .StartWithClassicDesktopLifetime(args); + public static void Main(string[] args) + { + BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); + } // Avalonia configuration, don't remove; also used by visual designer. public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure() .UsePlatformDetect() .WithInterFont() - .LogToTrace(); + .LogToNLog(); } diff --git a/SharpFM.App/nlog.config b/SharpFM.App/nlog.config index a30671f..dc6ab63 100644 --- a/SharpFM.App/nlog.config +++ b/SharpFM.App/nlog.config @@ -4,17 +4,15 @@ xsi:schemaLocation="NLog NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" - internalLogFile="c:\temp\console-example-internal.log" + internalLogFile="c:\temp\SharpFM-internal.log" internalLogLevel="Info"> - - + - @@ -23,6 +21,7 @@ +