Files
community/Ink Canvas/Helpers/LogHelper.cs
T

75 lines
2.4 KiB
C#
Raw Normal View History

2025-05-25 09:29:48 +08:00
using System;
2025-06-10 16:48:45 +08:00
using System.Diagnostics;
2025-05-25 09:29:48 +08:00
using System.IO;
2025-06-10 16:48:45 +08:00
using System.Threading;
2025-05-25 09:29:48 +08:00
namespace Ink_Canvas.Helpers
{
class LogHelper
{
public static string LogFile = "Log.txt";
public static void NewLog(string str)
{
WriteLogToFile(str, LogType.Info);
}
public static void NewLog(Exception ex)
{
2025-06-10 16:48:45 +08:00
if (ex == null) return;
var stackTrace = ex.StackTrace ?? "<no stack trace>";
var msg = $"[Exception] Type: {ex.GetType().FullName}\nMessage: {ex.Message}\nStackTrace: {stackTrace}";
if (ex.InnerException != null)
{
msg += $"\nInnerException: {ex.InnerException.GetType().FullName} - {ex.InnerException.Message}\n{ex.InnerException.StackTrace}";
}
WriteLogToFile(msg, LogType.Error);
2025-05-25 09:29:48 +08:00
}
public static void WriteLogToFile(string str, LogType logType = LogType.Info)
{
2025-06-10 16:48:45 +08:00
string strLogType = logType.ToString();
2025-05-25 09:29:48 +08:00
try
{
var file = App.RootPath + LogFile;
if (!Directory.Exists(App.RootPath))
{
Directory.CreateDirectory(App.RootPath);
}
2025-06-10 16:48:45 +08:00
var threadId = Thread.CurrentThread.ManagedThreadId;
var callingMethod = new StackTrace(2, true).GetFrame(0);
string callerInfo = "<unknown>";
if (callingMethod != null)
{
var method = callingMethod.GetMethod();
if (method != null)
{
var className = method.DeclaringType != null ? method.DeclaringType.FullName : "<no class>";
callerInfo = $"{className}.{method.Name}";
}
}
string logLine = string.Format("{0} [T{1}] [{2}] [{3}] {4}", DateTime.Now.ToString("O"), threadId, strLogType, callerInfo, str);
using (StreamWriter sw = new StreamWriter(file, true))
{
sw.WriteLine(logLine);
}
2025-05-25 09:29:48 +08:00
}
catch { }
}
internal static void WriteLogToFile(string v, object warning)
{
2025-06-10 16:48:45 +08:00
WriteLogToFile($"[Warning] {v}", LogType.Warning);
2025-05-25 09:29:48 +08:00
}
public enum LogType
{
Info,
Trace,
Error,
Event,
Warning
}
}
}