@@ -15,13 +15,20 @@ namespace DotNetCampus.Logging.Writers;
1515/// </summary>
1616public class ConsoleLogger : ILogger
1717{
18+ private static readonly TextWriter Out = GetStandardOutputWriter ( ) ;
19+
1820 /// <summary>
19- /// 控制台光标控制是否启用 。
21+ /// 用于处理重复的日志,避免重复日志污染控制台输出内容 。
2022 /// </summary>
21- private readonly bool _isCursorMovementEnabled ;
2223 private readonly RepeatLoggerDetector _repeat ;
23- private static bool _isConsoleOutput ;
24- private static readonly TextWriter Out = GetStandardOutputWriter ( ) ;
24+
25+ /// <summary>
26+ /// 判断当前是否在控制台输出日志(否则可能在普通的标准输入流,被其他应用程序对接)。
27+ /// </summary>
28+ /// <remarks>
29+ /// 如果在控制台输出,则可以使用 ASCII 控制码来修改颜色、控制光标移动。也可以用来获取控制台窗口信息。
30+ /// </remarks>
31+ private readonly bool _isConsoleOutput ;
2532
2633 /// <summary>
2734 /// 创建一个 <see cref="ConsoleLogger"/> 的新实例。
@@ -38,10 +45,7 @@ internal ConsoleLogger(ICoreLogWriter coreWriter, TagFilterManager? tagManager)
3845 _repeat = new RepeatLoggerDetector ( ClearAndMoveToLastLine ) ;
3946 CoreWriter = coreWriter ;
4047 TagManager = tagManager ;
41- _isConsoleOutput = Out == Console . Out ;
42- var success = ConsoleInitializer . Initialize ( ) ;
43- // 如果输出流是自己创建的,则不支持光标移动。
44- _isCursorMovementEnabled = _isConsoleOutput && success ;
48+ _isConsoleOutput = ConsoleInitializer . Initialize ( ) ;
4549 }
4650
4751 /// <summary>
@@ -179,7 +183,7 @@ string FirstLineFormatter(string m, int i) => logLevel is LogLevel.Critical
179183 /// <param name="repeatCount">此移动光标,是因为日志已重复第几次。</param>
180184 private void ClearAndMoveToLastLine ( int repeatCount )
181185 {
182- if ( ! _isCursorMovementEnabled )
186+ if ( ! _isConsoleOutput )
183187 {
184188 // 如果光标控制不可用,或者还没有重复次数,则不尝试移动光标。
185189 return ;
@@ -256,10 +260,12 @@ private int SafeGetBufferWidth()
256260 {
257261 try
258262 {
259- return _isCursorMovementEnabled ? Console . WindowWidth : 0 ;
263+ return _isConsoleOutput ? Console . WindowWidth : 0 ;
260264 }
261265 catch ( IOException )
262266 {
267+ // _isConsoleOutput 的条件已经非常苛刻了,足以确保 Console.WindowWidth 的获取不会出现异常。
268+ // 这只是保险性捕获。
263269 return 0 ;
264270 }
265271 }
0 commit comments