根据 ASP.NET 5 服务器类型打开控制台日志记录

Turn on Console Logging Based On ASP.NET 5 Server Type

如果应用程序是使用控制台启动的,我想添加控制台日志记录。有关 Logging in ASP.NET 5 的官方文档中的更多信息。如何判断应用程序是否在控制台下运行?

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    if (We are running under the console)
    {
        loggerFactory.AddConsole();
    }

    app.Run(async (context) =>
    {
        var logger = loggerFactory.CreateLogger("LoggingSample.Startup");
        logger.LogInformation("Writing output.");
        await context.Response.WriteAsync("Hello World!");
    });
}

如果你想在 运行 Kestrel 落后于 IIS/IIS Express 时排除日志记录,一种选择是使用 HttpPlatformHandler 本机模块添加的 HTTP_PLATFORM_PORT 环境变量:

if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HTTP_PLATFORM_PORT"))) {
    // Only enable logging when running Kestrel or WebListener
    // without IIS acting as a reverse-proxy.
}

可以使用应用程序构建器的 ServerFeatures 属性 来确定您的应用程序是否由 WebListener 托管:

if (app.ServerFeatures.Any(feature => feature.Key == typeof(WebListener))) {
    // Add server-specific features here.
}