-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogger.cs
69 lines (63 loc) · 1.89 KB
/
Logger.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
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
class Logger
{
private static readonly object lockObj = new object();
private static Logger instance = null;
private readonly string filePath;
private Logger(string fileName)
{
string directoryPath = Path.GetTempPath();
filePath = Path.Combine(directoryPath, fileName);
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
}
public static Logger GetInstance()
{
if (instance == null)
{
lock (lockObj)
{
if (instance == null)
{
int processId = Process.GetCurrentProcess().Id;
string fileName = $"sharpwin-debug-{DateTime.Now:yyyy-MM-dd-HH-mm-ss}_{processId}.log";
instance = new Logger(fileName);
}
}
}
return instance;
}
public async Task Log(string message)
{
#if DEBUG
// Utilize the asynchronous API for file operations
await WriteLogAsync(message);
#endif
}
private async Task WriteLogAsync(string message)
{
// Locking over a smaller scope
// We use a semaphore slim or another async-compatible locking mechanism if needed for finer control
lock (lockObj)
{
// Dummy lock to illustrate point, ideally we'd use SemaphoreSlim for async lock
}
try
{
// Async file write operation
using (StreamWriter writer = new StreamWriter(filePath, true))
{
await writer.WriteLineAsync(message);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error writing to log file: {ex.Message}");
}
}
}