-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogger.cs
131 lines (112 loc) · 3.39 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelpersLib
{
public class Logger
{
public delegate void MessageAddedEventHandler(string message);
public event MessageAddedEventHandler MessageAdded;
public bool Async { get; set; } = true;
public bool DebugWrite { get; set; } = true;
public bool StoreInMemory { get; set; } = true;
public bool FileWrite { get; set; } = false;
public string LogFilePath { get; private set; }
private readonly object loggerLock = new object();
private StringBuilder sbMessages = new StringBuilder();
public Logger()
{
}
public Logger(string logFilePath)
{
FileWrite = true;
LogFilePath = logFilePath;
Helpers.CreateDirectoryIfNotExist(LogFilePath);
}
protected void OnMessageAdded(string message)
{
if (MessageAdded != null)
{
MessageAdded(message);
}
}
public void WriteLine(string message)
{
if (!string.IsNullOrEmpty(message))
{
if (Async)
{
Task.Run(() => WriteLineInternal(message));
}
else
{
WriteLineInternal(message);
}
}
}
private void WriteLineInternal(string message)
{
lock (loggerLock)
{
message = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} - {message}";
if (DebugWrite)
{
Debug.WriteLine(message);
}
if (StoreInMemory && sbMessages != null)
{
sbMessages.AppendLine(message);
}
if (FileWrite && !string.IsNullOrEmpty(LogFilePath))
{
try
{
File.AppendAllText(LogFilePath, message + Environment.NewLine, Encoding.UTF8);
}
catch (Exception e)
{
Debug.WriteLine(e);
}
}
OnMessageAdded(message);
}
}
public void WriteLine(string format, params object[] args)
{
WriteLine(string.Format(format, args));
}
public void WriteException(string exception, string message = "Exception")
{
WriteLine("{0}:{1}{2}", message, Environment.NewLine, exception);
}
public void WriteException(Exception exception, string message = "Exception")
{
WriteException(exception.ToString(), message);
}
public void Clear()
{
lock (loggerLock)
{
if (sbMessages != null)
{
sbMessages.Clear();
}
}
}
public override string ToString()
{
lock (loggerLock)
{
if (sbMessages != null && sbMessages.Length > 0)
{
return sbMessages.ToString();
}
return null;
}
}
}
}