Logging information while debugging
Sometimes, it is inconvenient to place many breakpoints in the code to see how the application, or its particular module, is being executed. In such a case, it is a good idea to log various information and present it to the developer in the IDE in real time.
In this recipe, you will learn how to perform such a task using the Debug
class from the System.Diagnostics
namespace as well as present logs in the IDE within the Output window.
Getting ready
To complete this recipe, you need the project with two pages, represented by the MainPage
and ProductsPage
classes. It is necessary to pass a category identifier while navigating from MainPage
to ProductsPage
.
How to do it...
To prepare an example that shows how to log some data while debugging, you need to perform the following steps:
Open the
ProductsPage.xaml.cs
file.To log information after clicking on the button, but before coming back to the dashboard, modify the code of the
Button_Click
method, as follows:private void Button_Click(object sender, RoutedEventArgs e) { Debug.WriteLine("Coming back to the dashboard"); Frame.GoBack(); }
Tip
Do not forget to add the
using
statement for theSystem.Diagnostics
namespace, using the following line of code:using System.Diagnostics;
The IDE is equipped with a really nice feature that allows you to automatically insert a missing
using
statement. To do so, just left-click on the name of the unrecognized type and press Ctrl+ . (dot). In the pop-up window, you can find an option to automatically add a properusing
statement.To add conditional logging, activated only if the associated Boolean expression is evaluated to
true
, modify the code of theOnNavigatedTo
method in theProductsPage.xaml.cs
file, as follows:protected override void OnNavigatedTo( NavigationEventArgs e) { (...) Debug.WriteLine($"Presenting a list of products from category #{categoryId}"); Debug.WriteLineIf(categoryId < 0, $"Incorrect category identifier, namely {categoryId}"); }
Start debugging the application.
Open the Output window by navigating to Debug | Windows | Output from the menu. Then, click on the button in the emulator to see how the logs appear in the Output window. The exemplary result is shown as follows:
Presenting a list of products from category #1 Coming back to the dashboard.
See also
The Breakpoints-based debugging recipe
The Step-by-step debugging recipe
The Executing code while debugging recipe
The Creating a unit test and Running a set of tests recipes in Chapter 9, Testing and Submission