Log4CPPBase.cs
3.3 KB
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
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Text;
using System.Threading;
namespace eyemLib_Sharp.log4cpp
{
public abstract class Log4CPPBase : IDisposable
{
public Log4CPPBase()
{
m_FileLock = new ReaderWriteLock();
m_vec4Write = new ConcurrentQueue<string>();
ThreadPool.QueueUserWorkItem(new WaitCallback(Write), null);
}
private ReaderWriteLock m_FileLock;//文件锁
private ConcurrentQueue<string> m_vec4Write;
private CreateFileMode m_fileMode;
private int m_WriteStatus = 0;
//添加日志
public void WriteLog(string text)
{
m_vec4Write.Enqueue(text);
}
//写日志
private void Write(object obj)
{
while (true)
{
if (m_vec4Write.Count > 0)
{
string text = "";
m_vec4Write.TryDequeue(out text);
if (Interlocked.CompareExchange(ref m_WriteStatus, 1, 0) == 0)
{
WriteLogToFile(text);
}
}
Thread.Sleep(1);
}
}
protected virtual string GetLogFilePath()
{
return string.Empty;
}
private void WriteLogToFile(string text)
{
try
{
//进入文件锁
m_FileLock.EnterWriterLock();
//获取文件名
string logFullPath = GetLogFilePath();
if (!string.IsNullOrEmpty(logFullPath))
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(logFullPath, true, Encoding.UTF8);
if (text != null)
{
sw.WriteLine(text);
sw.Flush();
}
}
catch (Exception) { }
finally
{
if (sw != null)
{
sw.Close();
sw.Dispose();
sw = null;
}
m_FileLock.ReleaseWriterLock();
}
}
}
catch (Exception) { }
finally
{
Interlocked.Exchange(ref m_WriteStatus, 0);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);//防止Finalize调用
}
private bool m_disposed = false;//标识资源是否被释放过
protected virtual void Dispose(bool disposing)
{
if (!m_disposed)
{
if (disposing)
{
//释放托管资源
if (m_FileLock != null)
{
m_FileLock = null;
}
}
//释放非托管资源
m_disposed = true;
}
}
~Log4CPPBase()
{
Dispose(false);
}
}
}