-
Notifications
You must be signed in to change notification settings - Fork 0
/
XyLog.cs
116 lines (106 loc) · 3.44 KB
/
XyLog.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
113
114
115
116
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace xySoft.log
{
public static class XyLog
{
private static string _logDir = "log";
private static string _logFileName = "log";
static XyLog()
{
}
public static void init(string logDir, string logFileName)
{
_logDir = logDir;
_logFileName = logFileName;
}
private static Task? runningTask;
private static bool running = false;
public static void log(string logInfo)
{
lock (LogStringsDic)
{
LogStringsDic.Add(DateTime.Now, logInfo);
}
_ = Task.Run(async () => {
if(!running)
{
running = true;
if (runningTask != null)
{
await runningTask;
runningTask = null;
}
runningTask = Task.Run(() => {
runLog();
running = false;
});
}
});
}
public static void log(Exception e)
{
log(e.Message + " - " + e.StackTrace);
}
private static Dictionary<DateTime, string> LogStringsDic =
new Dictionary<DateTime, string>();
private static void runLog()
{
while (LogStringsDic.Count > 0)
{
DateTime logKey = LogStringsDic.Keys.First();
string logString = LogStringsDic[logKey];
lock (LogStringsDic)
{
LogStringsDic.Remove(logKey);
}
StreamWriter logWriter = getLogWriter(logKey);
logWriter.WriteLine(logKey + " -- " + logString);
logWriter.Flush();
}
}
private static StreamWriter? logWriter = null;
private static string currentDateString = "";
private static StreamWriter getLogWriter(DateTime lotDt)
{
string cateString = lotDt.ToString("yyyyMMdd");
if(currentDateString != cateString)
{
currentDateString = cateString;
string fileName =Path.Combine(
_logDir,
_logFileName.Split('.')[0] +
currentDateString + "." +
(
(_logFileName.Split('.').Length > 1) ?
_logFileName.Split('.')[1] : "log"
)
);
if (logWriter != null)
{
logWriter.Flush();
logWriter.Close();
}
if(!Directory.Exists(_logDir))
{
Directory.CreateDirectory(_logDir);
}
if (!File.Exists(fileName))
{
logWriter = new StreamWriter(fileName);
}
else
{
logWriter = File.AppendText(fileName);
logWriter.WriteLine("");
logWriter.Flush();
}
}
return logWriter!;
}
}
}