LenovoLegionToolkit
87 строк · 2.4 Кб
1using System;2using System.Collections.Generic;3using System.Diagnostics;4using System.IO;5using System.Runtime.CompilerServices;6using System.Text;7
8namespace LenovoLegionToolkit.Lib.Utils;9
10public class Log11{
12private static Log? _instance;13public static Log Instance14{15get16{17_instance ??= new Log();18return _instance;19}20}21
22private readonly object _lock = new();23private readonly string _folderPath;24private readonly string _logPath;25
26public bool IsTraceEnabled { get; set; }27
28public string LogPath => _logPath;29
30private Log()31{32_folderPath = Path.Combine(Folders.AppData, "log");33Directory.CreateDirectory(_folderPath);34_logPath = Path.Combine(_folderPath, $"log_{DateTime.UtcNow:yyyy_MM_dd_HH_mm_ss}.txt");35}36
37public void ErrorReport(string header, Exception ex)38{39var errorReportPath = Path.Combine(_folderPath, $"error_{DateTime.UtcNow:yyyy_MM_dd_HH_mm_ss}.txt");40File.AppendAllLines(errorReportPath, new[] { header, Serialize(ex) });41}42
43public void Trace(FormattableString message,44Exception? ex = null,45[CallerFilePath] string? file = null,46[CallerLineNumber] int lineNumber = -1,47[CallerMemberName] string? caller = null)48{49if (!IsTraceEnabled)50return;51
52LogInternal(_logPath, message, ex, file, lineNumber, caller);53}54
55private void LogInternal(string path,56FormattableString message,57Exception? ex,58string? file,59int lineNumber,60string? caller)61{62lock (_lock)63{64var lines = new List<string>65{66$"[{DateTime.UtcNow:dd/MM/yyyy HH:mm:ss.fff}] [{Environment.CurrentManagedThreadId}] [{Path.GetFileName(file)}#{lineNumber}:{caller}] {message}"67};68if (ex is not null)69lines.Add(Serialize(ex));70
71#if DEBUG72foreach (var line in lines)73Debug.WriteLine(line);74#endif75
76File.AppendAllLines(path, lines);77}78}79
80private static string Serialize(Exception ex) => new StringBuilder()81.AppendLine("=== Exception ===")82.AppendLine(ex.ToString())83.AppendLine()84.AppendLine("=== Exception demystified ===")85.AppendLine(ex.ToStringDemystified())86.ToString();87}
88