C# .Net程序如何同时捕获日志输出并保留终端原格式
保留终端颜色输出同时记录日志的解决方案
问题描述
我用C#代码通过PowerShell启动application.exe,想用Tee-Object同时把输出存到日志文件并输出到终端,但终端丢失了原有的颜色格式。直接运行application.exe时终端会显示彩色输出,可读性很强。请问怎么实现既保存输出到日志,又让终端输出保留格式?也接受其他终端方案。
原C#代码:
ProcessStartInfo psi = new ProcessStartInfo() { FileName = "powershell", Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"cd '{strLocation}'; & 'application.exe' 2>&1 | Tee-Object -File '{tempLogFilePath}'; Read-Host 'Press Enter to close...'\"", UseShellExecute = false, CreateNoWindow = false, // Show the terminal window };
解决方案
方法1:改用PowerShell 7+的Tee-Object(推荐)
Windows PowerShell 5.1及以下的Tee-Object会过滤ANSI颜色转义序列,但PowerShell 7及以上版本原生支持保留这些序列。只需将调用的powershell替换为pwsh(PowerShell Core的可执行文件):
ProcessStartInfo psi = new ProcessStartInfo() { FileName = "pwsh", // 切换到PowerShell 7+ Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"cd '{strLocation}'; & 'application.exe' 2>&1 | Tee-Object -File '{tempLogFilePath}'; Read-Host 'Press Enter to close...'\"", UseShellExecute = false, CreateNoWindow = false, };
此方案下,终端会保留彩色输出,日志文件也会存储完整的ANSI颜色码,后续可通过支持的工具查看带颜色的日志内容。
方法2:用第三方工具替代Tee-Object(适用于Windows PowerShell 5.1)
如果只能用Windows PowerShell,可以使用wintee这类第三方工具,它不会过滤ANSI颜色信息:
- 先安装
wintee(例如通过Chocolatey:choco install wintee) - 修改C#代码中的PowerShell命令:
ProcessStartInfo psi = new ProcessStartInfo() { FileName = "powershell", Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"cd '{strLocation}'; & 'application.exe' 2>&1 | wintee '{tempLogFilePath}'; Read-Host 'Press Enter to close...'\"", UseShellExecute = false, CreateNoWindow = false, };
方法3:通过CMD的tee命令实现
利用CMD原生的tee命令(不会过滤颜色码),绕开PowerShell管道的限制:
ProcessStartInfo psi = new ProcessStartInfo() { FileName = "powershell", Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"cd '{strLocation}'; & cmd /c 'application.exe 2>&1 | tee {tempLogFilePath}'; Read-Host 'Press Enter to close...'\"", UseShellExecute = false, CreateNoWindow = false, };
内容的提问来源于stack exchange,提问作者Eyal Gerber
相关产品推荐
相关产品推荐

