Date posted: 16 Apr 2020, 1 minutes to read

.NET Core: logging the configured URLs during starting of the application

Sometimes you want to log information during the startup of the web application. In our case we wanted to log some generic information about the server to see where we are in the process. Doing so proved a little more complicated than expected, so I needed to document this in case I need this in the future 😉.

Usually you can only find out the incoming URLs if you have a request you are handling, but during the startup phase in .NET core this is not possible. In ASP.NET you could do this with this call, but this is not available in .NET Core.

HttpRuntime.AppDomainAppVirtualPath

The solution

Below is the full setup we started using. We are using Serilog for structured logging and sending it to an ElasticSearch endpoint. Key part is of course in the call to the ServerFeatures: host.ServerFeatures.Get<IServerAddressesFeature>();

Full code example

Note: this code was tested with .NET Core 2.2.

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;

public static void Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(ConfigurationService.Configuration)
        .Enrich.WithElasticApmCorrelationInfo()
        .CreateLogger();

    try
    {
        Log.Information(
            "Starting {assembly} on {environment}",
            Assembly.GetCallingAssembly().GetName().Name,
            Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
        );

        var host = CreateWebHostBuilder(args).Build();
        var webAddresses = host.ServerFeatures.Get<IServerAddressesFeature>();
        foreach (var webAddress in webAddresses.Addresses)
        {
            Log.Information("WebAddress: {webAddress}", webAddress);
        }

        host.Run();
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "Application start-up failed");
    }
    finally
    {
        Log.CloseAndFlush();
    }
}