Skip to content

Commit

Permalink
introduce nlog with custom sink for avalonia
Browse files Browse the repository at this point in the history
  • Loading branch information
fuzzzerd committed Sep 29, 2023
1 parent 8a97f9d commit 8ac40a1
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 7 deletions.
57 changes: 57 additions & 0 deletions SharpFM.App/AvaloniaNLogSink.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System;
using Avalonia;
using Avalonia.Logging;
using NLog;

namespace SharpFM.App;

/// <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;
}
}
8 changes: 5 additions & 3 deletions SharpFM.App/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<App>()
.UsePlatformDetect()
.WithInterFont()
.LogToTrace();
.LogToNLog();
}
7 changes: 3 additions & 4 deletions SharpFM.App/nlog.config
Original file line number Diff line number Diff line change
Expand Up @@ -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">

<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<!-- write logs to the visual studio code "debug console" -->
<!-- write colorful logs to the console -->
<target name="logconsole" xsi:type="ColoredConsole" enableAnsiOutput="true"
layout="${time}|${uppercase:${level:padding=5}}|${mdlc:item=ScopeName}|${ndlctiming:currentScope=true}|${logger}|${message} ${exception:format=tostring:innerFormat=tostring:maxInnerExceptionLevel=2}"
useDefaultRowHighlightingRules="true">
<!-- explicitly use nlog color coding with a few adjustments for consistent display -->
<highlight-row condition="level == LogLevel.Fatal" foregroundColor="Red" />
<highlight-row condition="level == LogLevel.Error" foregroundColor="Yellow" />
<highlight-row condition="level == LogLevel.Warn" foregroundColor="Magenta" />
Expand All @@ -23,6 +21,7 @@
<highlight-row condition="level == LogLevel.Trace" foregroundColor="DarkGray" />
</target>

<!-- write logs to file in app data folder -->
<target xsi:type="File" name="logfile"
fileName="${specialfolder:folder=ApplicationData}\SharpFM.log"
layout="${longdate}|${uppercase:${level:padding=5}}|${mdlc:item=ScopeName}|${ndlctiming:currentScope=true}|${logger}|${message} ${exception:format=tostring:innerFormat=tostring:maxInnerExceptionLevel=2}" />
Expand Down

0 comments on commit 8ac40a1

Please sign in to comment.