How To Log Errors and Warnings
This guide shows you how to can log warnings and errors in Avalonia UI using the standard (Microsoft)System.Diagnostics.Trace component.
The code to achieve logging is added to your project by the Avalonia UI solution templates if you use them.
To enable, or to check that logging is enabled, follow this procedure:
- Locate the Program.cs file for your application.
- Check that the
BuildAvaloniaAppmethod callsLogToTrace, for example:
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace();
Without parameters, LogToTrace will log messages with a severity of Warning or higher. You can change this to another level by passing a LogLevel parameter to the LogToTrace call. For example:
using Avalonia.Logging;
...
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace(LogEventLevel.Verbose)
For the full API documentation on the LogEventLevel enum, see here.
Log messages are then shown in the Debug view of the Output window of your IDE. For example, with verbose logging enabled:
If you want to re-route these messages to different location, you can use the methods on the System.Diagnostics.Trace component.
Log Area
Each message from Avalonia UI is assigned an area that can be used to filter the log. These are described by the members of Avalonia.Logging.LogArea static class:
PropertyBindingAnimationsVisualLayoutControl
You can restrict the log to a specific area, or areas by adding arguments of type Avalonia.Logging.LogArea after the LogEventLevel argument in the LogToTrace call. For example, this will log only property and layout messages:
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace(LogEventLevel.Debug, LogArea.Property, LogArea.Layout);
Log Sinks
The LogToTrace extension method uses TraceLogSink which writes its messages to Trace. Avalonia supports custom sinks by implementing ILogSink. Assigning your custom sink to Avalonia.Logging.Logger.Sink will allow Avalonia to use it.
using Avalonia.Controls;
using Avalonia.Logging;
namespace MyNamespace;
public static class MyLogExtensions
{
public static AppBuilder LogToMySink(this AppBuilder builder,
LogEventLevel level = LogEventLevel.Warning,
params string[] areas)
{
Logger.Sink = new MyLogSink(level, areas);
return builder;
}
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToMySink();
View the source code on GitHub TraceLogSink.cs