-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLog.cs
77 lines (58 loc) · 2.13 KB
/
Log.cs
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
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Ascpixi.Wakatime.FLStudio;
public static class Log
{
static readonly Lock fileLock = new();
static bool canWriteToFile;
static readonly string dir = Path.Join(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"wakatime-flstudio"
);
public static readonly string FilePath = Path.Join(dir, "latest.log");
static Log()
{
if (File.Exists(FilePath)) {
string pathBase = Path.Combine(dir, $"{File.GetCreationTime(FilePath):yyyy-MM-dd}");
string newPath = pathBase + ".log";
if (File.Exists(newPath)) {
var seq = 1;
do {
newPath = $"{pathBase}-{seq++}.log";
} while (File.Exists(newPath));
}
Info($"Rotating old log to {newPath}.");
File.Move(FilePath, newPath);
}
else {
Directory.CreateDirectory(dir);
}
canWriteToFile = true;
}
static void Write(string severity, string msg)
{
var data = $"[{DateTime.Now:T}] ({severity}) {msg}";
if (canWriteToFile) {
lock (fileLock) {
File.AppendAllText(FilePath, data + Environment.NewLine);
}
}
Debug.WriteLine(data);
Console.WriteLine(data);
}
public static void Info(string msg) => Write("info", msg);
public static void Warning(string msg) => Write("warn", msg);
public static void Error(string msg) => Write("error", msg);
static string CreateWin32Message(string msg)
=> $"{msg} {Marshal.GetLastPInvokeErrorMessage()} (error {Marshal.GetLastWin32Error()})";
/// <summary>
/// Reports a warning caused by a Win32 call failing.
/// </summary>
public static void Win32Warning(string msg)
=> Warning(CreateWin32Message(msg));
/// <summary>
/// Reports an error caused by a Win32 call failing.
/// </summary>
public static void Win32Error(string msg)
=> Error(CreateWin32Message(msg));
}