当前位置:  开发笔记 > 编程语言 > 正文

我在哪里可以记录ASP.NET Core应用程序的启动/停止/错误事件?

如何解决《我在哪里可以记录ASP.NETCore应用程序的启动/停止/错误事件?》经验,为你挑选了2个好方法。

在旧的ASP.NET中,在Global.asax.cs类中,我会在应用程序启动时记录,停止并抛出未处理的异常:

Application_Start()

Application_End()

Application_Error()

我如何在ASP.NET Core中执行相同的操作?它有一个Startup类,但它用于配置.

我在哪里挂钩应用程序的开始/停止/错误事件?



1> Set..:

您需要使用Microsoft.AspNetCore.Hosting.IApplicationLifetime

    /// 
    /// Triggered when the application host has fully started and is about to wait
    /// for a graceful shutdown.
    /// 
    CancellationToken ApplicationStarted { get; }

    /// 
    /// Triggered when the application host is performing a graceful shutdown.
    /// Requests may still be in flight. Shutdown will block until this event completes.
    /// 
    CancellationToken ApplicationStopping { get; }

    /// 
    /// Triggered when the application host is performing a graceful shutdown.
    /// All requests should be complete at this point. Shutdown will block
    /// until this event completes.
    /// 
    CancellationToken ApplicationStopped { get; }

IApplicationLifetime的实例可以通过Configure方法获得.另外在这里添加ILoggerFactory:

public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory)
{
    // use applicationLifetime
}

拥有ILoggerFactory,您可以创建以下实例ILogger:

var logger = loggerFactory.CreateLogger("StartupLogger"); 

所以你只需要在Startup类中创建一个属性来持久保存实例ILogger(或者ILoggerFactory,如果你想为不同的事件创建不同的ligger实例).总结一下:

public class Startup 
{
    private ILogger _logger;

    public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory) 
    {
        applicationLifetime.ApplicationStopping.Register(OnShutdown);
        ... 
        // add logger providers
        // loggerFactory.AddConsole()
        ...
        _logger = loggerFactory.CreateLogger("StartupLogger");
    }

    private void OnShutdown()
    {
         // use _logger here;
    }
}



2> Jonas Stensv..:

请参阅CaptureStartupErrors和.CaptureStartupErrors(true)可帮助您发现问题的方法。

当某些东西在localhost上运行完美但在Azure中失败时,这特别方便。

这是我通常用于NetCore Web Apps的配置:

public static IWebHost BuildWebHost(string[] args) => WebHost
            .CreateDefaultBuilder(args)
            .CaptureStartupErrors(true)
            .UseKestrel()
            .UseIISIntegration()
            .UseStartup()
            .UseAzureAppServices()
            .Build();

然后,在Azure App Service中,您可以在Kudu工具中的日志流中找到日志 https://.scm.azurewebsites.net/api/logstream

推荐阅读
手机用户2402852387
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有