using System;
using System.IO;
namespace Project_Periodensystem.Model
{
///
/// Einfacher Logger für Debug-Ausgaben und Fehlerprotokollierung
///
public static class Logger
{
private static readonly string LogFilePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Periodensystem", "app.log");
///
/// Statischer Initializer - erstellt Log-Verzeichnis
///
static Logger()
{
try
{
var logDirectory = Path.GetDirectoryName(LogFilePath);
if (logDirectory != null && !Directory.Exists(logDirectory))
{
Directory.CreateDirectory(logDirectory);
}
}
catch
{
// Falls Log-Datei nicht erstellt werden kann, nur Konsole verwenden
}
}
///
/// Protokolliert eine Nachricht sowohl in Konsole als auch Datei
///
/// Zu protokollierende Nachricht
public static void Log(string message)
{
if (string.IsNullOrWhiteSpace(message))
return;
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
var logEntry = $"[{timestamp}] {message}";
// Konsolen-Ausgabe (für Debug)
Console.WriteLine(logEntry);
// Datei-Ausgabe (für Persistenz)
try
{
File.AppendAllText(LogFilePath, logEntry + Environment.NewLine);
}
catch
{
// Fehler beim Schreiben ignorieren um App nicht zum Absturz zu bringen
}
}
///
/// Protokolliert eine Exception mit Stack-Trace
///
/// Exception die protokolliert werden soll
/// Zusätzlicher Kontext
public static void LogException(Exception ex, string context = "")
{
if (ex == null)
{
Log("Null-Exception übergeben");
return;
}
var message = string.IsNullOrWhiteSpace(context)
? $"EXCEPTION: {ex.Message}\nStack: {ex.StackTrace}"
: $"EXCEPTION in {context}: {ex.Message}\nStack: {ex.StackTrace}";
Log(message);
}
///
/// Protokolliert eine Warnung
///
/// Warnung
public static void LogWarning(string message)
{
Log($"WARNING: {message}");
}
///
/// Protokolliert einen Fehler
///
/// Fehlermeldung
public static void LogError(string message)
{
Log($"ERROR: {message}");
}
///
/// Protokolliert Debug-Informationen (nur in Debug-Build)
///
/// Debug-Nachricht
[System.Diagnostics.Conditional("DEBUG")]
public static void LogDebug(string message)
{
Log($"DEBUG: {message}");
}
///
/// Löscht die Log-Datei (für Cleanup)
///
public static void ClearLog()
{
try
{
if (File.Exists(LogFilePath))
{
File.Delete(LogFilePath);
Log("Log-Datei gelöscht");
}
}
catch (Exception ex)
{
Log($"Fehler beim Löschen der Log-Datei: {ex.Message}");
}
}
///
/// Gibt den Pfad zur Log-Datei zurück
///
/// Vollständiger Pfad zur Log-Datei
public static string GetLogFilePath()
{
return LogFilePath;
}
}
}