Files
swyx/src/SwyxTray/Log.cs
T
Sven 78b17a1350 SwyxTray und Firefox-Plugin in das Repository aufnehmen
Windows-Tray-Anwendung (CLMgr-Anbindung an SwyxIt!) samt WebSocket-Zugang,
Firefox-Erweiterung und Browser-Beispielclient.
2026-08-21 11:33:52 +02:00

68 lines
1.9 KiB
C#

using System.Text;
namespace SwyxTray;
/// <summary>
/// Schlankes Dateiprotokoll unter %LOCALAPPDATA%\SwyxTray\. Bewusst ohne
/// Framework: die App hat kein Fenster, ein Protokoll ist deshalb das einzige
/// Mittel zur Fehlersuche.
/// </summary>
internal static class Log
{
private const long MaxBytes = 1024 * 1024;
private static readonly object Gate = new();
public static bool VerboseEnabled { get; set; }
public static string Directory { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"SwyxTray");
public static string FilePath { get; } = Path.Combine(Directory, "swyxtray.log");
public static void Debug(string message)
{
if (VerboseEnabled)
{
Write("DBG", message);
}
}
public static void Info(string message) => Write("INF", message);
public static void Error(string message, Exception? ex = null)
=> Write("ERR", ex is null ? message : $"{message} :: {ex}");
private static void Write(string level, string message)
{
var line = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{level}] {message}{Environment.NewLine}";
lock (Gate)
{
try
{
System.IO.Directory.CreateDirectory(Directory);
RollIfTooLarge();
File.AppendAllText(FilePath, line, Encoding.UTF8);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Ein fehlschlagendes Protokoll darf die App nicht beenden.
}
}
}
private static void RollIfTooLarge()
{
var info = new FileInfo(FilePath);
if (!info.Exists || info.Length < MaxBytes)
{
return;
}
var backup = FilePath + ".1";
File.Delete(backup);
File.Move(FilePath, backup);
}
}