-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppLogger.cs
More file actions
93 lines (77 loc) · 2.92 KB
/
AppLogger.cs
File metadata and controls
93 lines (77 loc) · 2.92 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
86
87
88
89
90
91
92
93
using System.Text;
namespace PDFtoPS;
internal sealed class AppLogger
{
private static readonly object Sync = new();
private readonly string logDirectory;
public AppLogger(string? baseDirectory = null)
{
logDirectory = ResolveWritableLogDirectory(baseDirectory);
}
public void Info(string message, params (string Key, object? Value)[] fields) => Write("INFO", message, fields);
public void Warning(string message, params (string Key, object? Value)[] fields) => Write("WARN", message, fields);
public void Error(string message, params (string Key, object? Value)[] fields) => Write("ERROR", message, fields);
private void Write(string level, string message, params (string Key, object? Value)[] fields)
{
StringBuilder line = new();
line.Append("ts=").Append(DateTime.Now.ToString("O"));
line.Append(" level=").Append(level);
line.Append(" msg=\"").Append(Escape(message)).Append('"');
foreach ((string key, object? value) in fields)
{
line.Append(' ')
.Append(key)
.Append("=\"")
.Append(Escape(value?.ToString() ?? string.Empty))
.Append('"');
}
string filePath = Path.Combine(logDirectory, $"{DateTime.Now:yyyyMMdd}.log");
try
{
lock (Sync)
{
Directory.CreateDirectory(logDirectory);
File.AppendAllText(filePath, line + Environment.NewLine, Encoding.UTF8);
}
}
catch
{
// Best-effort logging: never allow log I/O issues to break conversion flow.
}
}
private static string ResolveWritableLogDirectory(string? baseDirectory)
{
if (!string.IsNullOrWhiteSpace(baseDirectory))
{
string explicitPath = Path.Combine(baseDirectory, "logs");
if (TryEnsureDirectory(explicitPath)) return explicitPath;
}
string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (!string.IsNullOrWhiteSpace(localAppData))
{
string preferred = Path.Combine(localAppData, "PDFtoPS", "logs");
if (TryEnsureDirectory(preferred)) return preferred;
}
string appBase = Path.Combine(AppContext.BaseDirectory, "logs");
if (TryEnsureDirectory(appBase)) return appBase;
string tempFallback = Path.Combine(Path.GetTempPath(), "PDFtoPS", "logs");
TryEnsureDirectory(tempFallback);
return tempFallback;
}
private static bool TryEnsureDirectory(string path)
{
try
{
Directory.CreateDirectory(path);
return true;
}
catch
{
return false;
}
}
private static string Escape(string value)
{
return value.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace(Environment.NewLine, "\\n");
}
}