Logging in C#

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:

using System;
using System.Diagnostics;
using Microsoft.Extensions.Logging;

class Program
{
    static void Main(string[] args)
    {
        // We'll implement our logging examples here
    }
}

Now, let’s look at different logging methods:

// Simple debug output
Debug.WriteLine("standard debug output");

// Debug output with timestamp
Debug.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}: with timestamp");

// Debug output with method name and line number
Debug.WriteLine($"{nameof(Main)} at line {new StackFrame(true).GetFileLineNumber()}: with method/line");

For more advanced logging, we can use ILogger:

// Create a logger factory
using var loggerFactory = LoggerFactory.Create(builder =>
{
    builder
        .AddConsole()
        .SetMinimumLevel(LogLevel.Debug);
});

// Create a logger
var logger = loggerFactory.CreateLogger<Program>();

// Log a simple message
logger.LogInformation("from ILogger");

// Log with a scope
using (logger.BeginScope("CustomScope"))
{
    logger.LogInformation("This log is within a custom scope");
}

We can also create a custom logger with a specific category name:

var customLogger = loggerFactory.CreateLogger("CustomCategory");
customLogger.LogInformation("from custom category logger");

For structured logging, we can include key-value pairs:

logger.LogInformation("Structured log message {Key1} {Key2}", "Value1", 42);

To log to a file, we can use a third-party library like Serilog:

using Serilog;

Log.Logger = new LoggerConfiguration()
    .WriteTo.File("log.txt")
    .CreateLogger();

Log.Information("This will be written to the file");

Remember to clean up resources:

Log.CloseAndFlush();

To run this program, you’ll need to install the necessary NuGet packages:

dotnet add package Microsoft.Extensions.Logging
dotnet add package Microsoft.Extensions.Logging.Console
dotnet add package Serilog
dotnet add package Serilog.Sinks.File

Then compile and run the program:

$ dotnet run

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.