forked from LegoFigure11/RaidCrawler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogUtil.cs
More file actions
85 lines (73 loc) · 2.68 KB
/
LogUtil.cs
File metadata and controls
85 lines (73 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
namespace RaidCrawler.WinForms;
using System.Text;
using NLog;
using NLog.Config;
using NLog.Targets;
public static class LogUtil
{
static LogUtil()
{
var config = new LoggingConfiguration();
Directory.CreateDirectory("logs");
var logfile = new FileTarget("logfile")
{
FileName = Path.Combine("logs", "RaidCrawler.txt"),
ConcurrentWrites = true,
ArchiveEvery = FileArchivePeriod.Day,
ArchiveNumbering = ArchiveNumberingMode.Date,
ArchiveFileName = Path.Combine("logs", "RaidCrawler.{#}.txt"),
ArchiveDateFormat = "yyyy-MM-dd",
ArchiveAboveSize = 104857600, // 100MB (never)
MaxArchiveFiles = 14, // 2 weeks
Encoding = Encoding.Unicode,
WriteBom = true,
};
config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
LogManager.Configuration = config;
}
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
public static void LogText(string message) => Logger.Log(LogLevel.Info, message);
// hook in here if you want to forward the message elsewhere???
public static readonly List<Action<string, string>> Forwarders = new();
public static DateTime LastLogged { get; private set; } = DateTime.Now;
public static void LogError(string message, string identity)
{
Logger.Log(LogLevel.Error, $"{identity} {message}");
Log(message, identity);
}
public static void LogInfo(string message, string identity, bool logAlways = true)
{
Logger.Log(LogLevel.Info, $"{identity} {message}");
Log(message, identity, logAlways);
}
private static void Log(string message, string identity, bool logAlways = true)
{
foreach (var fwd in Forwarders)
{
try
{
if (logAlways)
fwd(message, identity);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
Logger.Log(LogLevel.Error, $"Failed to forward log from {identity} - {message}");
Logger.Log(LogLevel.Error, ex);
}
}
LastLogged = DateTime.Now;
}
public static void LogSafe(Exception exception, string identity)
{
Logger.Log(LogLevel.Error, $"Exception from {identity}:");
Logger.Log(LogLevel.Error, exception);
var err = exception.InnerException;
while (err is not null)
{
Logger.Log(LogLevel.Error, err);
err = err.InnerException;
}
}
}