Skip to content

Commit 466b03e

Browse files
committed
日志修改为线程安全写入
1 parent a33cf10 commit 466b03e

File tree

1 file changed

+27
-15
lines changed

1 file changed

+27
-15
lines changed

src/JiuLing.CommonLibs/Log/TextLogger.cs

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,12 @@ namespace JiuLing.CommonLibs.Log
77
/// <summary>
88
/// 文本日志
99
/// </summary>
10-
public class TextLogger : ILogger
10+
internal class TextLogger : ILogger
1111
{
1212
private string _logDirectory;
1313
private string _logNameDatetimeFormat;
1414
private string _logExpandedName;
15+
private static readonly object LockObj = new object();
1516
/// <summary>
1617
/// 实例化
1718
/// </summary>
@@ -33,8 +34,10 @@ public ILogger SetLogDirectory(string path)
3334
{
3435
throw new ArgumentException(nameof(path));
3536
}
36-
37-
_logDirectory = path;
37+
lock (LockObj)
38+
{
39+
_logDirectory = path;
40+
}
3841
return this;
3942
}
4043
/// <summary>
@@ -49,7 +52,10 @@ public ILogger SetFileNameFormat(string datetimeFormat)
4952
{
5053
throw new ArgumentException(nameof(datetimeFormat));
5154
}
52-
_logNameDatetimeFormat = datetimeFormat;
55+
lock (LockObj)
56+
{
57+
_logNameDatetimeFormat = datetimeFormat;
58+
}
5359
return this;
5460
}
5561
/// <summary>
@@ -64,7 +70,10 @@ public ILogger SetFileExpandedName(string expandedName)
6470
{
6571
throw new ArgumentException(nameof(expandedName));
6672
}
67-
_logExpandedName = expandedName;
73+
lock (LockObj)
74+
{
75+
_logExpandedName = expandedName;
76+
}
6877
return this;
6978
}
7079
/// <summary>
@@ -73,19 +82,22 @@ public ILogger SetFileExpandedName(string expandedName)
7382
/// <param name="message"></param>
7483
public void Write(string message)
7584
{
76-
if (!Directory.Exists(_logDirectory))
85+
lock (LockObj)
7786
{
78-
Directory.CreateDirectory(_logDirectory);
79-
}
87+
if (!Directory.Exists(_logDirectory))
88+
{
89+
Directory.CreateDirectory(_logDirectory);
90+
}
8091

81-
DateTime now = DateTime.Now;
82-
string fileName = $"{now.ToString(_logNameDatetimeFormat)}{_logExpandedName}";
83-
string path = Path.Combine(_logDirectory, fileName);
92+
DateTime now = DateTime.Now;
93+
string fileName = $"{now.ToString(_logNameDatetimeFormat)}{_logExpandedName}";
94+
string path = Path.Combine(_logDirectory, fileName);
8495

85-
using (StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.UTF8))
86-
{
87-
sw.Write($"{now:yyyy-MM-dd HH:mm:ss.fff} {message}{Environment.NewLine}");
88-
sw.Flush();
96+
using (StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.UTF8))
97+
{
98+
sw.Write($"{now:yyyy-MM-dd HH:mm:ss.fff} {message}{Environment.NewLine}");
99+
sw.Flush();
100+
}
89101
}
90102
}
91103
}

0 commit comments

Comments
 (0)