1
1
using System ;
2
2
using System . IO ;
3
+ using System . Text ;
3
4
using dotnetCampus . Logging . Writers . Helpers ;
4
5
using C = dotnetCampus . Logging . Writers . ConsoleLoggerHelpers . ConsoleColors ;
5
6
using B = dotnetCampus . Logging . Writers . ConsoleLoggerHelpers . ConsoleColors . Background ;
@@ -16,9 +17,11 @@ public class ConsoleLogger : ILogger
16
17
/// <summary>
17
18
/// 控制台光标控制是否启用。目前可容纳的错误次数为 3 次,当降低到 0 次时,将不再尝试移动光标。
18
19
/// </summary>
19
- private int _isCursorMovementEnabled = 3 ;
20
+ private int _isCursorMovementEnabled ;
20
21
21
22
private readonly RepeatLoggerDetector _repeat ;
23
+ private static bool _isConsoleOutput ;
24
+ private static readonly TextWriter Out = GetStandardOutputWriter ( ) ;
22
25
23
26
/// <summary>
24
27
/// 创建一个 <see cref="ConsoleLogger"/> 的新实例。
@@ -35,6 +38,9 @@ internal ConsoleLogger(ICoreLogWriter coreWriter, TagFilterManager? tagManager)
35
38
_repeat = new RepeatLoggerDetector ( ClearAndMoveToLastLine ) ;
36
39
CoreWriter = coreWriter ;
37
40
TagManager = tagManager ;
41
+ _isConsoleOutput = Out == Console . Out ;
42
+ // 如果输出流是自己创建的,则不支持光标移动。
43
+ _isCursorMovementEnabled = _isConsoleOutput ? 3 : 0 ;
38
44
}
39
45
40
46
/// <summary>
@@ -105,7 +111,14 @@ private void LogCore(LogLevel logLevel, Exception? exception, string message, Fu
105
111
{
106
112
if ( _repeat . RepeatOrResetLastLog ( logLevel , message , exception ) is var count and > 1 )
107
113
{
108
- ConsoleMultilineMessage ( $ "上述日志已重复 { count } 次", formatter , true ) ;
114
+ if ( _isConsoleOutput )
115
+ {
116
+ ConsoleMultilineMessage ( $ "上述日志已重复 { count } 次", formatter , true ) ;
117
+ }
118
+ else
119
+ {
120
+ ConsoleMultilineMessage ( message , m => $ "{ formatter ( m ) } { F . BrightBlack } (重复 { count } 次){ Reset } ", true ) ;
121
+ }
109
122
}
110
123
else if ( exception is null )
111
124
{
@@ -157,7 +170,7 @@ internal static void SafeWriteLine(string? message)
157
170
{
158
171
try
159
172
{
160
- Console . WriteLine ( message ) ;
173
+ Out . WriteLine ( message ) ;
161
174
}
162
175
catch ( IOException )
163
176
{
@@ -198,6 +211,26 @@ private void ClearAndMoveToLastLine(int repeatCount)
198
211
}
199
212
}
200
213
214
+ /// <summary>
215
+ /// 获取标准输出的写入流。<br/>
216
+ /// 如果当前在控制台中输出,则使用控制台的输出流;否则创建一个 UTF-8 编码的标准输出流。
217
+ /// </summary>
218
+ /// <returns>文本写入流。</returns>
219
+ private static TextWriter GetStandardOutputWriter ( )
220
+ {
221
+ if ( Console . OutputEncoding . CodePage is not 0 )
222
+ {
223
+ return Console . Out ;
224
+ }
225
+
226
+ var standardOutput = Console . OpenStandardOutput ( ) ;
227
+ var writer = new StreamWriter ( standardOutput , Encoding . UTF8 )
228
+ {
229
+ AutoFlush = true ,
230
+ } ;
231
+ return writer ;
232
+ }
233
+
201
234
private const string Reset = C . Reset ;
202
235
private const string TraceText = F . Magenta ;
203
236
private const string DebugText = F . White ;
0 commit comments