Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

feat: improve error logging (#125)

lars-bergerecec72b6787f
diff --git a/GlazeWM.Bootstrapper/Startup.cs b/GlazeWM.Bootstrapper/Startup.cs
index 326043ff..68bb6751 100644
--- a/GlazeWM.Bootstrapper/Startup.cs
+++ b/GlazeWM.Bootstrapper/Startup.cs
@@ -1,12 +1,17 @@
using GlazeWM.Bar;
using GlazeWM.Domain.Common.Commands;
+using GlazeWM.Domain.Containers;
using GlazeWM.Domain.Windows.Commands;
using GlazeWM.Infrastructure.Bussing;
+using GlazeWM.Infrastructure.Serialization;
using GlazeWM.Infrastructure.WindowsApi;
using GlazeWM.Infrastructure.WindowsApi.Events;
using System;
+using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Reactive.Linq;
+using System.Text.Json.Serialization;
using System.Windows.Forms;
using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;
@@ -15,6 +20,8 @@ namespace GlazeWM.Bootstrapper
internal class Startup
{
private readonly Bus _bus;
+ private readonly ContainerService _containerService;
+ private readonly JsonService _jsonService;
private readonly KeybindingService _keybindingService;
private readonly WindowEventService _windowEventService;
private readonly BarService _barService;
@@ -23,6 +30,8 @@ namespace GlazeWM.Bootstrapper
public Startup(
Bus bus,
+ ContainerService containerService,
+ JsonService jsonService,
KeybindingService keybindingService,
WindowEventService windowEventService,
BarService barService,
@@ -30,6 +39,8 @@ namespace GlazeWM.Bootstrapper
SystemEventService systemEventService)
{
_bus = bus;
+ _containerService = containerService;
+ _jsonService = jsonService;
_keybindingService = keybindingService;
_windowEventService = windowEventService;
_barService = barService;
@@ -42,6 +53,10 @@ namespace GlazeWM.Bootstrapper
// Set the process-default DPI awareness.
_ = SetProcessDpiAwarenessContext(DpiAwarenessContext.Context_PerMonitorAwareV2);
+ _bus.FatalException.Subscribe(_ => WriteStateDumpToErrorLog());
+ _bus.Events.OfType<ApplicationExitingEvent>()
+ .Subscribe(_ => OnApplicationExit());
+
// Launch bar WPF application. Spawns bar window when monitors are added, so the service needs
// to be initialized before populating initial state.
_barService.StartApp();
@@ -61,9 +76,6 @@ namespace GlazeWM.Bootstrapper
// Add application to system tray.
_systemTrayService.AddToSystemTray();
- _bus.Events.Where(@event => @event is ApplicationExitingEvent)
- .Subscribe(_ => OnApplicationExit());
-
Application.Run();
}
@@ -76,5 +88,26 @@ namespace GlazeWM.Bootstrapper
// TODO: Use exit code 1 if exiting due to an unhandled error.
Environment.Exit(0);
}
+
+ // TODO: Move to dedicated logging service.
+ private void WriteStateDumpToErrorLog()
+ {
+ var errorLogPath = Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
+ "./.glaze-wm/errors.log"
+ );
+
+ Directory.CreateDirectory(Path.GetDirectoryName(errorLogPath));
+
+ try
+ {
+ var stateDump = _jsonService.Serialize(_containerService.ContainerTree, new List<JsonConverter> { new JsonContainerConverter() });
+ File.AppendAllText(errorLogPath, $"\nState dump: {stateDump}");
+ }
+ catch (Exception)
+ {
+ File.AppendAllText(errorLogPath, "\nFailed to get state dump.");
+ }
+ }
}
}
diff --git a/GlazeWM.Domain/JsonContainerConverter.cs b/GlazeWM.Domain/JsonContainerConverter.cs
new file mode 100644
index 00000000..db859ca3
--- /dev/null
+++ b/GlazeWM.Domain/JsonContainerConverter.cs
@@ -0,0 +1,161 @@
+using System;
+using System.Linq;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using GlazeWM.Domain.Common.Enums;
+using GlazeWM.Domain.Monitors;
+using GlazeWM.Domain.Windows;
+using GlazeWM.Domain.Workspaces;
+using GlazeWM.Infrastructure.Serialization;
+using GlazeWM.Infrastructure.WindowsApi;
+
+namespace GlazeWM.Domain.Containers
+{
+ public class JsonContainerConverter : JsonConverter<Container>
+ {
+ public override Container Read(
+ ref Utf8JsonReader reader,
+ Type typeToConvert,
+ JsonSerializerOptions options)
+ {
+ using var jsonDocument = JsonDocument.ParseValue(ref reader);
+
+ return DeserializeContainerJson(jsonDocument.RootElement, options);
+ }
+
+ private static Container DeserializeContainerJson(
+ JsonElement jsonObject,
+ JsonSerializerOptions options,
+ Container parent = null)
+ {
+ // Get the type of container (eg. "Workspace", "MinimizedWindow").
+ var typeDiscriminator = jsonObject.GetProperty("__type").ToString();
+
+ var newContainer = typeDiscriminator switch
+ {
+ "Container" => new Container(),
+ "Monitor" => new Monitor(
+ jsonObject.GetProperty("DeviceName").GetString(),
+ jsonObject.GetProperty("Width").GetInt32(),
+ jsonObject.GetProperty("Height").GetInt32(),
+ jsonObject.GetProperty("X").GetInt32(),
+ jsonObject.GetProperty("Y").GetInt32()
+ ),
+ "Workspace" => new Workspace(
+ jsonObject.GetProperty("Name").GetString()
+ ),
+ "SplitContainer" => new SplitContainer
+ {
+ Layout = jsonObject.GetProperty("Layout").Deserialize<Layout>(),
+ SizePercentage = jsonObject.GetProperty("SizePercentage").GetDouble()
+ },
+ "MinimizedWindow" => new MinimizedWindow(
+ // TODO: Handle `IntPtr` for 32-bit processes.
+ new IntPtr(Convert.ToInt64(jsonObject.GetProperty("Hwnd").GetString(), 16)),
+ jsonObject.GetProperty("FloatingPlacement").Deserialize<WindowRect>(),
+ jsonObject.GetProperty("BorderDelta").Deserialize<RectDelta>(),
+ jsonObject.GetEnumProperty<WindowType>("PreviousState", options)
+ ),
+ "FloatingWindow" => new FloatingWindow(
+ // TODO: Handle `IntPtr` for 32-bit processes.
+ new IntPtr(Convert.ToInt64(jsonObject.GetProperty("Hwnd").GetString(), 16)),
+ jsonObject.GetProperty("FloatingPlacement").Deserialize<WindowRect>(),
+ jsonObject.GetProperty("BorderDelta").Deserialize<RectDelta>()
+ ),
+ "TilingWindow" => new TilingWindow(
+ // TODO: Handle `IntPtr` for 32-bit processes.
+ new IntPtr(Convert.ToInt64(jsonObject.GetProperty("Hwnd").GetString(), 16)),
+ jsonObject.GetProperty("FloatingPlacement").Deserialize<WindowRect>(),
+ jsonObject.GetProperty("BorderDelta").Deserialize<RectDelta>(),
+ jsonObject.GetProperty("SizePercentage").GetDouble()
+ ),
+ _ => throw new ArgumentException(null, nameof(jsonObject)),
+ };
+
+ newContainer.Parent = parent;
+
+ var children = jsonObject.GetProperty("Children").EnumerateArray();
+ newContainer.Children = children
+ .Select((child) => DeserializeContainerJson(child, options, newContainer))
+ .ToList();
+
+ var focusIndices =
+ children.Select(child => child.GetProperty("FocusIndex").GetInt32());
+
+ // Map focus index to the corresponding child container.
+ newContainer.ChildFocusOrder = focusIndices
+ .Select(focusIndex => newContainer.Children[focusIndex])
+ .ToList();
+
+ return newContainer;
+ }
+
+ public override void Write(
+ Utf8JsonWriter writer,
+ Container value,
+ JsonSerializerOptions options)
+ {
+ writer.WriteStartObject();
+ writer.WriteNumber("X", value.X);
+ writer.WriteNumber("Y", value.Y);
+ writer.WriteNumber("Width", value.Width);
+ writer.WriteNumber("Height", value.Height);
+ writer.WriteString("__type", value.GetType().Name);
+
+ // Handle focus index for root container.
+ var focusIndex = value.Parent is not null ? value.FocusIndex : 0;
+ writer.WriteNumber("FocusIndex", focusIndex);
+
+ switch (value)
+ {
+ case Monitor:
+ var monitor = value as Monitor;
+ writer.WriteString("DeviceName", monitor.DeviceName);
+ break;
+ case Workspace:
+ var workspace = value as Workspace;
+ writer.WriteString("Name", workspace.Name);
+ break;
+ case SplitContainer:
+ var splitContainer = value as SplitContainer;
+ writer.WriteString("Layout", splitContainer.Layout.ToString());
+ writer.WriteNumber("SizePercentage", splitContainer.SizePercentage);
+ break;
+ case MinimizedWindow:
+ var minimizedWindow = value as MinimizedWindow;
+ writer.WriteString("Hwnd", minimizedWindow.Hwnd.ToString("x"));
+ writer.WritePropertyName("FloatingPlacement");
+ JsonSerializer.Serialize(writer, minimizedWindow.FloatingPlacement);
+ writer.WritePropertyName("BorderDelta");
+ JsonSerializer.Serialize(writer, minimizedWindow.BorderDelta);
+ writer.WriteString("PreviousState", minimizedWindow.PreviousState.ToString());
+ break;
+ case FloatingWindow:
+ var floatingWindow = value as FloatingWindow;
+ writer.WriteString("Hwnd", floatingWindow.Hwnd.ToString("x"));
+ writer.WritePropertyName("FloatingPlacement");
+ JsonSerializer.Serialize(writer, floatingWindow.FloatingPlacement);
+ writer.WritePropertyName("BorderDelta");
+ JsonSerializer.Serialize(writer, floatingWindow.BorderDelta);
+ break;
+ case TilingWindow:
+ var tilingWindow = value as TilingWindow;
+ writer.WriteString("Hwnd", tilingWindow.Hwnd.ToString("x"));
+ writer.WritePropertyName("FloatingPlacement");
+ JsonSerializer.Serialize(writer, tilingWindow.FloatingPlacement);
+ writer.WritePropertyName("BorderDelta");
+ JsonSerializer.Serialize(writer, tilingWindow.BorderDelta);
+ writer.WriteNumber("SizePercentage", tilingWindow.SizePercentage);
+ break;
+ }
+
+ // Recursively serialize child containers.
+ writer.WriteStartArray("Children");
+ foreach (var child in value.Children)
+ Write(writer, child, options);
+
+ writer.WriteEndArray();
+ writer.WriteEndObject();
+ }
+ }
+}
diff --git a/GlazeWM.Infrastructure/Bussing/Bus.cs b/GlazeWM.Infrastructure/Bussing/Bus.cs
index 1ca40ac0..94a5bc11 100644
--- a/GlazeWM.Infrastructure/Bussing/Bus.cs
+++ b/GlazeWM.Infrastructure/Bussing/Bus.cs
@@ -4,6 +4,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.IO;
using System.Reactive.Subjects;
using System.Windows.Forms;
@@ -16,6 +17,7 @@ namespace GlazeWM.Infrastructure.Bussing
public sealed class Bus
{
public readonly Subject<Event> Events = new();
+ public readonly Subject<bool> FatalException = new();
private readonly object _lockObj = new();
private readonly ILogger<Bus> _logger;
@@ -93,7 +95,7 @@ namespace GlazeWM.Infrastructure.Bussing
}
// TODO: Move to dedicated logging service.
- private static void WriteToErrorLog(Exception error)
+ private void WriteToErrorLog(Exception error)
{
var errorLogPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
@@ -101,7 +103,11 @@ namespace GlazeWM.Infrastructure.Bussing
);
Directory.CreateDirectory(Path.GetDirectoryName(errorLogPath));
- File.AppendAllText(errorLogPath, $"\n\n{DateTime.Now}\n{error.Message + error.StackTrace}");
+ File.AppendAllText(errorLogPath, $"\n\n{DateTime.Now}\n{error.Message + error.ToString()}");
+ File.AppendAllText(errorLogPath, "\n-- END OF INNER EXCEPTION --");
+ File.AppendAllText(errorLogPath, $"\n{new StackTrace(3, true)}");
+
+ FatalException.OnNext(true);
}
}
}
diff --git a/GlazeWM.Infrastructure/Serialization/JsonElementExtensions.cs b/GlazeWM.Infrastructure/Serialization/JsonElementExtensions.cs
new file mode 100644
index 00000000..a5008495
--- /dev/null
+++ b/GlazeWM.Infrastructure/Serialization/JsonElementExtensions.cs
@@ -0,0 +1,62 @@
+using System;
+using System.Text.Json;
+
+namespace GlazeWM.Infrastructure.Serialization
+{
+ public static class JsonElementExtensions
+ {
+ /// <summary>
+ /// Get JSON property where property name has been converted according to naming policy.
+ /// </summary>
+ private static JsonElement GetConvertedProperty(
+ this JsonElement element,
+ string propertyName,
+ JsonSerializerOptions options)
+ {
+ // Convert name according to given naming policy.
+ var convertedName =
+ options.PropertyNamingPolicy?.ConvertName(propertyName) ?? propertyName;
+
+ return element.GetProperty(convertedName);
+ }
+
+ public static string GetStringProperty(
+ this JsonElement element,
+ string propertyName,
+ JsonSerializerOptions options)
+ {
+ return element.GetConvertedProperty(propertyName, options).GetString();
+ }
+
+ public static int GetInt64Property(
+ this JsonElement element,
+ string propertyName,
+ JsonSerializerOptions options)
+ {
+ return element.GetConvertedProperty(propertyName, options).GetInt32();
+ }
+
+ public static double GetDoubleProperty(
+ this JsonElement element,
+ string propertyName,
+ JsonSerializerOptions options)
+ {
+ return element.GetConvertedProperty(propertyName, options).GetDouble();
+ }
+
+ public static T GetEnumProperty<T>(
+ this JsonElement element,
+ string propertyName,
+ JsonSerializerOptions options) where T : struct, Enum
+ {
+ T value;
+ Enum.TryParse<T>(element.GetProperty(propertyName).GetString(), out value);
+ return value;
+ }
+
+ private static string ConvertName(string propertyName, JsonSerializerOptions options)
+ {
+ return options.PropertyNamingPolicy?.ConvertName(propertyName) ?? propertyName;
+ }
+ }
+}