forked from Ken98045/On-Guard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dbg.cs
111 lines (97 loc) · 2.58 KB
/
Dbg.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
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.IO;
namespace SAAI
{
/// <summary>
/// A class for writing debug information. We queue the string (with date and time)
/// We write it out on a different thread. We may add the ability to write it to a file.
/// </summary>
public static class Dbg
{
static readonly ConcurrentQueue<string> q = new ConcurrentQueue<string>();
static readonly ManualResetEvent activity = new ManualResetEvent(false);
static public ManualResetEvent Stop { get; } = new ManualResetEvent(false);
static readonly Thread processThread = new Thread(ProcessOutput);
static TextWriter s_LogWriter;
public static int LogLevel { get; set; }
static string s_path;
// DebugWriter.Write
static Dbg()
{
LogLevel = 0;
s_path = Storage.GetFilePath("OnGuard.txt");
processThread.Start();
}
static public void Write(string debugString)
{
string str = string.Format("{0} - {1}", DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff"), debugString);
q.Enqueue(str);
activity.Set();
}
static public void Trace(string debugString)
{
if (LogLevel > 0)
{
Write("(Trace) " + debugString);
}
}
static public bool DeleteLogFile()
{
bool result = false;
int tryCount = 0;
while (tryCount < 5)
{
try
{
if (null == s_LogWriter)
{
File.Delete(s_path);
s_LogWriter = null;
}
result = true;
break;
}
catch (IOException)
{
Thread.Sleep(100);
++tryCount;
}
}
return result;
}
static void ProcessOutput()
{
WaitHandle[] waits = new WaitHandle[2];
waits[0] = Stop;
waits[1] = activity;
while (!Stop.WaitOne(0))
{
while (WaitHandle.WaitAny(waits) != 0)
{
if (q.TryDequeue(out string output))
{
Console.WriteLine(output);
if (s_LogWriter == null)
{
s_LogWriter = new StreamWriter(s_path, true);
}
s_LogWriter.WriteLine(output);
s_LogWriter.Flush();
}
else
{
activity.Reset();
s_LogWriter.Close();
s_LogWriter = null;
}
}
}
if (s_LogWriter != null)
{
s_LogWriter.Close();
}
}
}
}