Skip to content

Commit 2ebc50a

Browse files
committed
支持简单的日志级别
1 parent 1f235db commit 2ebc50a

File tree

4 files changed

+163
-21
lines changed

4 files changed

+163
-21
lines changed

src/JiuLing.CommonLibs/Log/ILogger.cs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
namespace JiuLing.CommonLibs.Log
1+
using System;
2+
3+
namespace JiuLing.CommonLibs.Log
24
{
35
/// <summary>
46
/// 日志接口
@@ -10,20 +12,37 @@ public interface ILogger
1012
/// </summary>
1113
/// <returns></returns>
1214
ILogger SetLogDirectory(string path);
15+
1316
/// <summary>
1417
/// 设置日志文件名的格式
1518
/// </summary>
1619
/// <returns></returns>
1720
ILogger SetFileNameFormat(string datetimeFormat);
21+
1822
/// <summary>
1923
/// 设置日志文件扩展名
2024
/// </summary>
2125
/// <returns></returns>
2226
ILogger SetFileExpandedName(string expandedName);
27+
2328
/// <summary>
2429
/// 写日志
2530
/// </summary>
2631
/// <param name="message">日志内容</param>
32+
[Obsolete("请使用 Info() 方法替代。")]
2733
void Write(string message);
34+
35+
/// <summary>
36+
/// 写入消息日志
37+
/// </summary>
38+
/// <param name="message">日志内容</param>
39+
void Info(string message);
40+
41+
/// <summary>
42+
/// 写入错误日志
43+
/// </summary>
44+
/// <param name="message">日志内容</param>
45+
/// <param name="ex">异常信息</param>
46+
void Error(string message, Exception ex = null);
2847
}
2948
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace JiuLing.CommonLibs.Log
6+
{
7+
/// <summary>
8+
/// 日志级别
9+
/// </summary>
10+
internal enum LogLevel
11+
{
12+
/// <summary>
13+
/// 消息
14+
/// </summary>
15+
Info,
16+
/// <summary>
17+
/// 错误
18+
/// </summary>
19+
Error
20+
}
21+
}

src/JiuLing.CommonLibs/Log/LogManager.cs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
namespace JiuLing.CommonLibs.Log
1+
using System;
2+
3+
namespace JiuLing.CommonLibs.Log
24
{
35
/// <summary>
46
/// 日志管理
@@ -26,5 +28,17 @@ public static ILogger GetLogger()
2628
return _logger;
2729
}
2830
}
31+
32+
/// <summary>
33+
/// 注册日志写入异常回调
34+
/// </summary>
35+
/// <param name="callback">异常处理回调</param>
36+
public static void RegisterLogExceptionCallback(Action<Exception> callback)
37+
{
38+
if (_logger is TextLogger)
39+
{
40+
TextLogger.OnLogWriteException += callback;
41+
}
42+
}
2943
}
3044
}

src/JiuLing.CommonLibs/Log/TextLogger.cs

Lines changed: 107 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,28 @@ internal class TextLogger : ILogger
1212
private string _logDirectory;
1313
private string _logNameDatetimeFormat;
1414
private string _logExpandedName;
15+
/// <summary>
16+
/// 不同日志级别是否单独记录到不同文件
17+
/// </summary>
18+
private bool _separateByLogLevel;
1519
private static readonly object LockObj = new object();
20+
21+
/// <summary>
22+
/// 异常回调,供LogManager注册使用
23+
/// </summary>
24+
internal static Action<Exception> OnLogWriteException { get; set; }
25+
1626
/// <summary>
1727
/// 实例化
1828
/// </summary>
1929
public TextLogger()
2030
{
21-
_logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
31+
_logDirectory = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log"));
2232
_logNameDatetimeFormat = "yyyy-MM-dd";
2333
_logExpandedName = ".log";
34+
_separateByLogLevel = true;
2435
}
36+
2537
/// <summary>
2638
/// 设置日志目录
2739
/// </summary>
@@ -32,14 +44,17 @@ public ILogger SetLogDirectory(string path)
3244
{
3345
if (path.IsEmpty())
3446
{
35-
throw new ArgumentException(nameof(path));
47+
throw new ArgumentException("日志路径不能为空", nameof(path));
3648
}
49+
3750
lock (LockObj)
3851
{
39-
_logDirectory = path;
52+
_logDirectory = Path.GetFullPath(path);
4053
}
54+
4155
return this;
4256
}
57+
4358
/// <summary>
4459
/// 设置日志文件名格式
4560
/// </summary>
@@ -50,14 +65,27 @@ public ILogger SetFileNameFormat(string datetimeFormat)
5065
{
5166
if (datetimeFormat.IsEmpty())
5267
{
53-
throw new ArgumentException(nameof(datetimeFormat));
68+
throw new ArgumentException("时间格式化规则不能为空", nameof(datetimeFormat));
69+
}
70+
71+
// 尝试格式化当前时间,校验格式是否合法
72+
try
73+
{
74+
DateTime.Now.ToString(datetimeFormat);
75+
}
76+
catch (FormatException)
77+
{
78+
throw new ArgumentException("时间格式无法格式化", nameof(datetimeFormat));
5479
}
80+
5581
lock (LockObj)
5682
{
5783
_logNameDatetimeFormat = datetimeFormat;
5884
}
85+
5986
return this;
6087
}
88+
6189
/// <summary>
6290
/// 设置日志文件扩展名
6391
/// </summary>
@@ -68,37 +96,97 @@ public ILogger SetFileExpandedName(string expandedName)
6896
{
6997
if (expandedName.IsEmpty())
7098
{
71-
throw new ArgumentException(nameof(expandedName));
99+
throw new ArgumentException("扩展名不能为空", nameof(expandedName));
72100
}
101+
73102
lock (LockObj)
74103
{
75-
_logExpandedName = expandedName;
104+
_logExpandedName = expandedName.StartsWith(".") ? expandedName : "." + expandedName;
76105
}
106+
77107
return this;
78108
}
109+
110+
/// <summary>
111+
/// 设置是否按日志等级分文件
112+
/// </summary>
113+
/// <param name="separate">是否按等级分文件</param>
114+
/// <returns></returns>
115+
public ILogger SetSeparateByLogLevel(bool separate)
116+
{
117+
lock (LockObj)
118+
{
119+
_separateByLogLevel = separate;
120+
}
121+
122+
return this;
123+
}
124+
79125
/// <summary>
80126
/// 写入日志
81127
/// </summary>
82-
/// <param name="message"></param>
128+
/// <param name="message">日志内容</param>
129+
[Obsolete("请使用 Info() 方法替代。")]
83130
public void Write(string message)
84131
{
85-
lock (LockObj)
132+
Info(message);
133+
}
134+
135+
/// <summary>
136+
/// 写入消息日志
137+
/// </summary>
138+
/// <param name="message">日志内容</param>
139+
public void Info(string message)
140+
{
141+
WriteInner(LogLevel.Info, message);
142+
}
143+
144+
/// <summary>
145+
/// 写入错误日志
146+
/// </summary>
147+
/// <param name="message">日志内容</param>
148+
/// <param name="ex">异常信息</param>
149+
public void Error(string message, Exception ex = null)
150+
{
151+
if (ex != null)
86152
{
87-
if (!Directory.Exists(_logDirectory))
153+
message = $"{message}{Environment.NewLine}Exception: {ex.Message}{Environment.NewLine}StackTrace: {ex.StackTrace}";
154+
}
155+
WriteInner(LogLevel.Error, message);
156+
}
157+
158+
/// <summary>
159+
/// 写入日志
160+
/// </summary>
161+
/// <param name="level">消息级别</param>
162+
/// <param name="message">日志内容</param>
163+
private void WriteInner(LogLevel level, string message)
164+
{
165+
try
166+
{
167+
lock (LockObj)
88168
{
89-
Directory.CreateDirectory(_logDirectory);
90-
}
169+
if (!Directory.Exists(_logDirectory))
170+
{
171+
Directory.CreateDirectory(_logDirectory);
172+
}
91173

92-
DateTime now = DateTime.Now;
93-
string fileName = $"{now.ToString(_logNameDatetimeFormat)}{_logExpandedName}";
94-
string path = Path.Combine(_logDirectory, fileName);
174+
DateTime now = DateTime.Now;
175+
string prefix = _separateByLogLevel ? level.ToString().ToLower() : "all";
176+
string fileName = $"{prefix}_{now.ToString(_logNameDatetimeFormat)}{_logExpandedName}";
177+
string path = Path.Combine(_logDirectory, fileName);
95178

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();
179+
using (var sw = new StreamWriter(path, true, System.Text.Encoding.UTF8))
180+
{
181+
sw.Write($"{now:yyyy-MM-dd HH:mm:ss.fff} [{level}] {message}{Environment.NewLine}");
182+
sw.Flush();
183+
}
100184
}
101185
}
186+
catch (Exception ex)
187+
{
188+
OnLogWriteException?.Invoke(ex);
189+
}
102190
}
103191
}
104-
}
192+
}

0 commit comments

Comments
 (0)