LenovoLegionToolkit

Форк
0
87 строк · 2.4 Кб
1
using System;
2
using System.Collections.Generic;
3
using System.Diagnostics;
4
using System.IO;
5
using System.Runtime.CompilerServices;
6
using System.Text;
7

8
namespace LenovoLegionToolkit.Lib.Utils;
9

10
public class Log
11
{
12
    private static Log? _instance;
13
    public static Log Instance
14
    {
15
        get
16
        {
17
            _instance ??= new Log();
18
            return _instance;
19
        }
20
    }
21

22
    private readonly object _lock = new();
23
    private readonly string _folderPath;
24
    private readonly string _logPath;
25

26
    public bool IsTraceEnabled { get; set; }
27

28
    public string LogPath => _logPath;
29

30
    private Log()
31
    {
32
        _folderPath = Path.Combine(Folders.AppData, "log");
33
        Directory.CreateDirectory(_folderPath);
34
        _logPath = Path.Combine(_folderPath, $"log_{DateTime.UtcNow:yyyy_MM_dd_HH_mm_ss}.txt");
35
    }
36

37
    public void ErrorReport(string header, Exception ex)
38
    {
39
        var errorReportPath = Path.Combine(_folderPath, $"error_{DateTime.UtcNow:yyyy_MM_dd_HH_mm_ss}.txt");
40
        File.AppendAllLines(errorReportPath, new[] { header, Serialize(ex) });
41
    }
42

43
    public void Trace(FormattableString message,
44
        Exception? ex = null,
45
        [CallerFilePath] string? file = null,
46
        [CallerLineNumber] int lineNumber = -1,
47
        [CallerMemberName] string? caller = null)
48
    {
49
        if (!IsTraceEnabled)
50
            return;
51

52
        LogInternal(_logPath, message, ex, file, lineNumber, caller);
53
    }
54

55
    private void LogInternal(string path,
56
        FormattableString message,
57
        Exception? ex,
58
        string? file,
59
        int lineNumber,
60
        string? caller)
61
    {
62
        lock (_lock)
63
        {
64
            var lines = new List<string>
65
            {
66
                $"[{DateTime.UtcNow:dd/MM/yyyy HH:mm:ss.fff}] [{Environment.CurrentManagedThreadId}] [{Path.GetFileName(file)}#{lineNumber}:{caller}] {message}"
67
            };
68
            if (ex is not null)
69
                lines.Add(Serialize(ex));
70

71
#if DEBUG
72
            foreach (var line in lines)
73
                Debug.WriteLine(line);
74
#endif
75

76
            File.AppendAllLines(path, lines);
77
        }
78
    }
79

80
    private 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

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.