-
Notifications
You must be signed in to change notification settings - Fork 1
/
DualWriter.cs
68 lines (58 loc) · 1.56 KB
/
DualWriter.cs
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
using System;
using System.IO;
using System.Text;
public class DualWriter : TextWriter
{
private readonly TextWriter _originalConsoleOut;
private readonly StreamWriter _fileWriter;
private readonly string _logFilePath;
public DualWriter(string logFilePath)
{
_logFilePath = logFilePath;
// 删除之前的日志文件
if (File.Exists(_logFilePath))
{
File.Delete(_logFilePath);
}
_originalConsoleOut = Console.Out;
_fileWriter = new StreamWriter(_logFilePath, true)
{
AutoFlush = true // 确保每次写入后立即刷新
};
}
public override Encoding Encoding => _originalConsoleOut.Encoding;
public override void Write(char value)
{
_originalConsoleOut.Write(value);
WriteToFile(value.ToString());
}
public override void Write(string value)
{
_originalConsoleOut.Write(value);
WriteToFile(value);
}
public override void WriteLine(string value)
{
_originalConsoleOut.WriteLine(value);
WriteToFile(value + Environment.NewLine);
}
private void WriteToFile(string text)
{
try
{
_fileWriter.Write(text);
}
catch (Exception ex)
{
_originalConsoleOut.WriteLine($"写入日志文件时发生错误: {ex.Message}");
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_fileWriter?.Dispose();
}
base.Dispose(disposing);
}
}