练习 - 日志记录和跟踪

已完成

现在,已开始开发应用程序,可以向逻辑添加其他诊断了,以便帮助开发人员添加新功能。 我们可以使用调试诊断的新知识来完成此任务。

写入调试控制台

在调试应用程序之前,让我们添加其他调试诊断。 当应用程序在调试模式下运行时,其他诊断将有助于诊断应用程序。

Program.cs 文件的顶部,我们将添加一个新的 using 语句以引入 System.Diagnostics,以便我们可以使用 Debug 方法。

using System.Diagnostics;

WriteLine 语句添加到 Fibonacci 方法的开头,以便在调试代码时清楚地进行展示。

Debug.WriteLine($"Entering {nameof(Fibonacci)} method");
Debug.WriteLine($"We are looking for the {n}th number");

for 循环结束时,我们可以打印出每个值。 我们也可以使用条件打印语句,其方法是通过使用 WriteIfWriteLineIf 以仅当 sum 在循环末尾为 1 时添加打印行:

for (int i = 2; i <= n; i++)
{                  
    sum = n1 + n2;
    n1 = n2;
    n2 = sum;
    Debug.WriteLineIf(sum == 1, $"sum is 1, n1 is {n1}, n2 is {n2}");    
}

调试应用程序,应会显示以下输出:

Entering Fibonacci method
We are looking for the 5th number
sum is 1, n1 is 1, n2 is 1

检查带有断言的条件

在某些情况下,当不满足特定条件时,可能需要停止整个正在运行的应用程序。 使用 Debug.Assert 可以检查条件并输出有关应用程序状态的其他信息。 让我们在 return 语句之前添加检查,以确保 n2 为 5。

// If n2 is 5 continue, else break.
Debug.Assert(n2 == 5, "The return value is not 5 and it should be.");
return n == 0 ? n1 : n2;

我们的应用程序逻辑已经是正确的,接下来,让我们将 Fibonacci(5); 更新为 Fibonacci(6);,其结果会有所不同。

调试应用程序。 当在代码中运行 Debug.Assert 时,调试器将停止应用程序,以便可以检查变量、监视窗口、调用堆栈等。 它还会将消息输出到调试控制台。

---- DEBUG ASSERTION FAILED ----
---- Assert Short Message ----
The return value is not 5 and it should be.
---- Assert Long Message ----

   at Program.<<Main>$>g__Fibonacci|0_0(Int32 n) in C:\Users\Jon\Desktop\DotNetDebugging\Program.cs:line 23
   at Program.<Main>$(String[] args) in C:\Users\Jon\Desktop\DotNetDebugging\Program.cs:line 3

停止调试,然后通过在终端中输入以下命令,在不调试的情况下运行应用程序。

dotnet run

应用程序在断言失败后终止,并且已将信息记录到应用程序输出。

Process terminated. Assertion failed.
The return value is not 5 and it should be.
   at Program.<<Main>$>g__Fibonacci|0_0(Int32 n) in C:\Users\Jon\Desktop\DotNetDebugging\Program.cs:line 23
   at Program.<Main>$(String[] args) in C:\Users\Jon\Desktop\DotNetDebugging\Program.cs:line 3

现在,让我们在终端中输入以下命令,以便在 Release 配置中运行应用程序。

dotnet run --configuration Release

应用程序已成功运行到完成,因为我们不再处于 Debug 配置中。

恭喜,你已成功有效地使用 .NET 的功能(包括 Debug.WriteLineDebug.Assert)调试了代码。 干得不错!