-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLogManager.cs
91 lines (81 loc) · 2.29 KB
/
LogManager.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
78
79
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.IO;
using System.Threading.Tasks;
namespace TheGuide
{
internal sealed class LogManager
{
private static readonly string BaseDir = Path.Combine(AppContext.BaseDirectory, "dist");
private static readonly string LogDir = Path.Combine(BaseDir, "logs");
private string LogPath => Path.Combine(LogDir, LogFilePath());
private readonly string _suffix;
private readonly string _prefix;
private readonly object _locker = new object();
private DateTime CurrentDate() => DateTime.Now;
private string LogFilePath() => $"{_prefix ?? ""}{CurrentDate():dd-MM-yyyy}{_suffix ?? ""}.txt";
public LogManager(string prefix = null, string suffix = null)
{
this._prefix = prefix;
this._suffix = suffix;
}
private Task Maintain()
{
Directory.CreateDirectory(LogDir);
if (!File.Exists(LogPath))
File.Create(LogPath).Dispose();
return Task.CompletedTask;
}
public async Task Write(string logMessage)
{
await Maintain();
FileAppend(_locker, LogPath, logMessage + "\r\n");
}
public static string FileReadToEnd(object locker, string filePath)
{
string buffer;
lock (locker)
{
using (var stream = File.Open(filePath, FileMode.Open))
using (var reader = new StreamReader(stream))
buffer = reader.ReadToEnd();
}
return buffer;
}
public static void FileWrite(object locker, string path, string content)
{
lock (locker)
{
using (var stream = File.Open(path, FileMode.Create))
using (var writer = new StreamWriter(stream))
writer.Write(content);
}
}
public static void FileWriteLine(object locker, string path, string content)
{
lock (locker)
{
using (var stream = File.Open(path, FileMode.Create))
using (var writer = new StreamWriter(stream))
writer.WriteLine(content);
}
}
public static void FileAppend(object locker, string path, string content)
{
lock (locker)
{
using (var stream = File.Open(path, FileMode.Append))
using (var writer = new StreamWriter(stream))
writer.Write(content);
}
}
public static void FileAppendLine(object locker, string path, string content)
{
lock (locker)
{
using (var stream = File.Open(path, FileMode.Append))
using (var writer = new StreamWriter(stream))
writer.WriteLine(content);
}
}
}
}