Skip to content

Instantly share code, notes, and snippets.

@spacetrack
Last active October 18, 2022 03:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spacetrack/4021bee26453e01a89db2c5ed378d385 to your computer and use it in GitHub Desktop.
Save spacetrack/4021bee26453e01a89db2c5ed378d385 to your computer and use it in GitHub Desktop.
.NET 6 Minimal Web API with Endpoint Logging

.NET 6 Minimal Web API with Endpoint Logging

with your project set to C# 10 (add <LangVersion>preview</LangVersion> to your .csproj file), in your Program.cs simply add ILogger<Program> logger to your endpoint delegate:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace MinimalWebApiWithLogging
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            var app = builder.Build();

            app.MapGet("/hello/{name}", (ILogger<Program> logger, string name) =>
            {
                logger.LogInformation("say hello to {name} ...", name);
                return Results.Text($"hello {name}");
            });

            app.Logger.LogInformation("starting the app ...");
            app.Run();
        }
    }
}

... yes, C# 10 allows you to remove all boiler plate code, so only lines 18 - 28 will remain ;-)



spacetrack.github.io

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment