-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogger.cs
66 lines (59 loc) · 1.77 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
using System;
using System.IO;
using System.Threading;
namespace Common
{
public class Logger
{
public enum LogLevel
{
None,
Trace,
Debug
}
public LogLevel Level { get; set; } = LogLevel.None;
public string Filepath { get; set; }
public bool Append { get; set; }
public Logger(string filepath, LogLevel level, bool append = true) : this(filepath)
{
Level = level;
Append = append;
if (File.Exists(filepath) && !Append)
{
File.Delete(filepath);
}
}
public Logger(string filepath)
{
Filepath = filepath;
var path = Path.GetDirectoryName(filepath);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
if (!Directory.Exists(path))
throw new Exception($"Unable to create path: {path}");
}
}
private static ReaderWriterLockSlim locker = new ReaderWriterLockSlim();
public void Write(LogLevel level, string info)
{
//var dir = Environment.CurrentDirectory;
if (Level != LogLevel.None && level <= Level)
{
locker.EnterWriteLock();
try
{
using (var writer = new StreamWriter(Filepath, true))
{
var line = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} {level}: {info}";
writer.WriteLine(line);
}
}
finally
{
locker.ExitWriteLock();
}
}
}
}
}