75 lines
2.4 KiB
C#
75 lines
2.4 KiB
C#
using System;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Threading;
|
|
|
|
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)
|
|
{
|
|
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);
|
|
}
|
|
|
|
public static void WriteLogToFile(string str, LogType logType = LogType.Info)
|
|
{
|
|
string strLogType = logType.ToString();
|
|
try
|
|
{
|
|
var file = App.RootPath + LogFile;
|
|
if (!Directory.Exists(App.RootPath))
|
|
{
|
|
Directory.CreateDirectory(App.RootPath);
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
internal static void WriteLogToFile(string v, object warning)
|
|
{
|
|
WriteLogToFile($"[Warning] {v}", LogType.Warning);
|
|
}
|
|
|
|
public enum LogType
|
|
{
|
|
Info,
|
|
Trace,
|
|
Error,
|
|
Event,
|
|
Warning
|
|
}
|
|
}
|
|
}
|