Write the crash synchronously from App.UnhandledException so a startup crash leaves its exception in LocalState\widget.log. Co-Authored-By: Claude Opus 5.5 <[email protected]>
62 lines
2.0 KiB
C#
62 lines
2.0 KiB
C#
using System;
|
|
using System.Globalization;
|
|
using System.IO;
|
|
using System.Threading.Tasks;
|
|
using Windows.Storage;
|
|
|
|
namespace CrossSoundWidget.Services
|
|
{
|
|
/// <summary>
|
|
/// A small connection log in the package's LocalState folder
|
|
/// (%LOCALAPPDATA%\Packages\RedLintu16.CrossSoundWidget_jdapqa6743p5g\LocalState\widget.log),
|
|
/// trimmed when it passes 256 KB. For diagnosing "it won't connect" after the fact.
|
|
/// </summary>
|
|
public static class Log
|
|
{
|
|
private static readonly object Gate = new object();
|
|
private static string _path;
|
|
|
|
public static void Write(string message)
|
|
{
|
|
var line = Format(message);
|
|
Task.Run(() => Append(line));
|
|
}
|
|
|
|
/// <summary>Synchronous, for a crash handler: the process may be gone before a Task runs.</summary>
|
|
public static void WriteNow(string message)
|
|
{
|
|
Append(Format(message));
|
|
}
|
|
|
|
private static string Format(string message)
|
|
{
|
|
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)
|
|
+ " [" + Environment.CurrentManagedThreadId.ToString(CultureInfo.InvariantCulture) + "] "
|
|
+ message + Environment.NewLine;
|
|
}
|
|
|
|
private static void Append(string line)
|
|
{
|
|
try
|
|
{
|
|
lock (Gate)
|
|
{
|
|
if (_path == null) _path = Path.Combine(ApplicationData.Current.LocalFolder.Path, "widget.log");
|
|
var info = new FileInfo(_path);
|
|
if (info.Exists && info.Length > 256 * 1024)
|
|
{
|
|
var old = _path + ".1";
|
|
if (File.Exists(old)) File.Delete(old);
|
|
File.Move(_path, old);
|
|
}
|
|
File.AppendAllText(_path, line);
|
|
}
|
|
}
|
|
catch (Exception)
|
|
{
|
|
// Logging must never break the widget.
|
|
}
|
|
}
|
|
}
|
|
}
|