C# 调试技巧——日志记录,NuGet内断点
在C#中,Debug.WriteLine()
、Trace.WriteLine()
和 Console.WriteLine()
都用于输出信息,但它们的用途和适用场景有显著区别。以下是它们的核心差异总结:
Debug.WriteLine()
主要适用于控制台程序,输出到控制台Trace.WriteLine()
开发阶段调试输出Console.WriteLine()
运行时状态,适合记录程序运行状态、错误日志等持久化信息。
不同模式调试信息打印
新建一个winform窗体
添加一下事件记录信息,测试Debug模式和Release模式下,打印区别
结论:Debug模式下,Debug和Trace都打印,Release模式下只打印Trace
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace DebugApp
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){Debug.WriteLine("Debug button1_Click");Trace.WriteLine("Trace button1_Click");}/// <summary>/// 窗体加载/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Form1_Load(object sender, EventArgs e){Debug.WriteLine("Debug Form1_Load");Trace.WriteLine("Trace Form1_Load");}/// <summary>/// 窗体关闭/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Form1_FormClosed(object sender, FormClosedEventArgs e){Debug.WriteLine("Debug Form1_FormClosed");Trace.WriteLine("Trace Form1_FormClosed");}}
}
调试记录打印
怎样将我们需要的信息打印出来,
在 app.config/web.config 中配置 Trace 监听器
<?xml version="1.0" encoding="utf-8" ?>
<configuration><startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" /></startup><!-- 在 app.config/web.config 中配置 Trace 监听器 --><system.diagnostics><trace autoflush="true"><listeners><add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="log.txt" /></listeners></trace></system.diagnostics>
</configuration>
将会在运行目录下,新建一个log.txt文件,将Trace和Debug信息打印
怎样在NuGet包或dll中打断点调试
已经优化过的代码,不支持,
点击工具-选项 找到调试里面的开启仅我代码就可以在调试的时候只加载用户代码的符号,关掉就可以调试其他代码