Here’s the translation of the Go logging example to C#, formatted in Markdown suitable for Hugo:
Our example demonstrates various logging techniques in C#. We’ll use the built-in System.Diagnostics.Debug class for debug output, and the more flexible Microsoft.Extensions.Logging for structured logging.
First, let’s set up our project and import necessary namespaces:
Now, let’s look at different logging methods:
For more advanced logging, we can use ILogger:
We can also create a custom logger with a specific category name:
For structured logging, we can include key-value pairs:
To log to a file, we can use a third-party library like Serilog:
Remember to clean up resources:
To run this program, you’ll need to install the necessary NuGet packages:
Then compile and run the program:
The output will depend on your logging configuration, but you should see various log messages in the console and in the log.txt file.
This example demonstrates basic logging, structured logging, and file logging in C#. The ILogger interface provides a flexible and extensible logging framework, while libraries like Serilog offer additional features for more complex logging scenarios.