This repository was archived by the owner on Jul 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLog.cs
98 lines (82 loc) · 2.07 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
using System;
using System.Collections.Generic;
using System.IO;
namespace HatlessEngine
{
/// <summary>
/// Contains methods to write (log) messages in a standardized way.
/// </summary>
public static class Log
{
private static bool _consoleEnabled = false;
private static TextWriter _consoleWriter;
private static bool _fileEnabled = false;
private static StreamWriter _fileWriter;
public static List<StreamWriter> CustomStreams = new List<StreamWriter>();
public static void Message(string message, LogLevel logLevel = LogLevel.Debug, bool timeStamp = true)
{
string formattedMessage = "";
if (timeStamp)
formattedMessage += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ";
if (logLevel != LogLevel.None)
formattedMessage += "[" + logLevel + "] ";
formattedMessage += message;
if (_consoleEnabled)
_consoleWriter.WriteLine(formattedMessage);
if (_fileEnabled)
_fileWriter.WriteLine(formattedMessage);
foreach (StreamWriter stream in CustomStreams)
stream.WriteLine(formattedMessage);
}
public static void EnableConsole()
{
if (_consoleEnabled)
return;
_consoleWriter = Console.Out;
_consoleEnabled = true;
}
public static void DisableConsole()
{
if (!_consoleEnabled)
return;
_consoleWriter.Close();
_consoleWriter = null;
_consoleEnabled = false;
}
public static void EnableFile(string filename)
{
if (_fileEnabled)
return;
_fileWriter = new StreamWriter(File.Open(filename, FileMode.Append, FileAccess.Write, FileShare.Read));
_fileEnabled = true;
}
public static void DisableFile()
{
if (!_fileEnabled)
return;
_fileWriter.Close();
_fileWriter = null;
_fileEnabled = false;
}
/// <summary>
/// For cleanup before exiting.
/// </summary>
internal static void CloseAllStreams()
{
DisableConsole();
DisableFile();
foreach (StreamWriter stream in CustomStreams)
stream.Close();
CustomStreams.Clear();
}
}
public enum LogLevel
{
None = 0,
Debug = 1,
Notice = 2,
Warning = 3,
Critical = 4,
Fatal = 5
}
}