-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLog.cs
109 lines (97 loc) · 3.22 KB
/
Log.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
namespace WA2AD
{
//
// This is a singleton so use it like:
//
// Log.Write(Log.Level.Informational, "Heeeyyyy there!");
//
// If you want to write to the event log, include this in your
// program:
//
// EventLogTraceListener myTraceListener = new EventLogTraceListener("WA2AD");
// Trace.Listeners.Add(myTraceListener);
//
// Note that you may need to register the application name beforehand, so run this
// in an admin-level powershell:
//
// New-EventLog -LogName Application -Source "WA2AD"
//
public sealed class Log
{
public enum Level
{
Informational,
Warning,
Error
}
private static string logFilename = "wa2ad.log";
private static Object logFileLock = new Object();
private static bool logToFile = false;
private static readonly Lazy<Log> log = new Lazy<Log>(() => new Log());
public static Log Instance { get { return log.Value; } }
private static String GetTimestamp(DateTime value)
{
return value.ToString("MM/dd/yyyy HH:mm:ss.ffff");
}
public static void Write(Level level, string logEntry)
{
Console.ResetColor();
string ts = GetTimestamp(DateTime.Now);
string logLine = ts + " - " + logEntry;
switch (level)
{
case Level.Informational:
Trace.TraceInformation(logEntry);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(logLine);
break;
case Level.Warning:
Trace.TraceWarning(logEntry);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(logLine);
break;
case Level.Error:
Trace.TraceError(logEntry);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(logLine);
break;
}
Console.ResetColor();
if (logToFile)
{
lock (logFileLock)
{
// And let's write to a file
using (StreamWriter sw = File.AppendText(logFilename))
{
sw.WriteLine(logLine);
}
}
}
}
static Log()
{
var MyIni = new IniFile();
string logToFileFlag = MyIni.Read("EnableFileLogging").Trim();
if (logToFileFlag == "1")
{
Console.Write("=== Okay, let's truncate the old log file...");
FileStream oStream = File.Open(logFilename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
oStream.SetLength(0);
oStream.Close();
logToFile = true;
}
}
private Log()
{
}
}
}