You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将C# Trace和Debug信息重定向至文件?

问题原因及解决方案

你的问题根源在于日志输出的流选择:配置里的LogToStandardErrorThreshold = LogLevel.Trace,会把所有Trace、Debug级别的日志输出到标准错误流(stderr),而你用的PowerShell命令默认只处理标准输出流(stdout),所以抓不到这些日志。

解决方法有两种:

1. 调整C#日志配置,让Trace/Debug输出到stdout

修改控制台日志的错误阈值,把LogToStandardErrorThreshold设为更高的级别(比如LogLevel.Error),这样Trace、Debug、Info、Warning级别的日志都会输出到stdout,就能被tee和Start-Transcript正常捕获:

.ConfigureLogging(logging =>  
{
    logging.SetMinimumLevel(LogLevel.Trace);
    logging.AddConsole(o => o.LogToStandardErrorThreshold = LogLevel.Error);
}

2. 在PowerShell中同时捕获stdout和stderr

如果不想改代码,直接在命令里把stderr重定向到stdout即可:

  • 用tee的话:
    myprogram 2>&1 | tee -FilePath $name
    
    这里2>&1是PowerShell的重定向语法,把标准错误流(编号2)合并到标准输出流(编号1)。
  • 用Start-Transcript的话:
    Start-Transcript -Path "C:\logs\output.log"; myprogram 2>&1; Stop-Transcript
    

内容的提问来源于stack exchange,提问作者ca9163d9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 08:52:03