-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogger.cs
112 lines (93 loc) · 3.32 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TypicalReply.Config;
namespace TypicalReply
{
internal static class Logger
{
private static int MaxGeneration = 10;
private static long MaxLogSize = 10 * 1024 * 1024;
private static string LogFileNameBase = "TypicalReply";
private static string FilePath = Path.Combine(StandardPath.GetUserDir(), "TypicalReply.log");
private static StreamWriter LogStream { get; set; }
private static object LockObject = new object();
internal static void Log(string message) => NoException(() => LogImpl(message));
internal static void Log(Exception e) => NoException(() => LogImpl(e));
private static void NoException(Action func)
{
try { func(); } catch { }
}
private static void LogImpl(string message)
{
lock (LockObject)
{
RotateIfNeed();
LogStream.WriteLine($"{GetTimestamp()} : {message}");
LogStream.Flush();
}
}
private static void LogImpl(Exception e)
{
LogImpl(e.ToString());
}
private static string GetTimestamp()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
private static void RotateIfNeed()
{
if (!File.Exists(FilePath))
{
LogStream?.Close();
LogStream = null;
}
if (LogStream is null)
{
LogStream = new StreamWriter(new FileStream(FilePath, FileMode.OpenOrCreate));
}
var fi = new FileInfo(FilePath);
if(fi.Length > MaxLogSize)
{
Rotate();
}
}
private static void Rotate()
{
lock (LockObject)
{
LogStream?.Close();
string previousFileName;
string previousFilePath;
string rotatedFileName;
string rotatedFilePath;
string userDir = StandardPath.GetUserDir();
for (int i = MaxGeneration - 1; i >= 0; i--)
{
if (i > 0)
{
previousFileName = $"{LogFileNameBase}_{i}.log";
}
else
{
previousFileName = $"{LogFileNameBase}.log";
}
previousFilePath = Path.Combine(userDir, previousFileName);
if (!File.Exists(previousFilePath))
{
continue;
}
rotatedFileName = $"{LogFileNameBase}_{ i + 1 }.log";
rotatedFilePath = Path.Combine(userDir, rotatedFileName);
File.Copy(previousFilePath, rotatedFilePath, true);
File.Delete(previousFilePath);
}
LogStream = new StreamWriter(new FileStream(FilePath, FileMode.Create));
}
}
}
}