简体   繁体   English

.net 5 登录到 azure 应用程序服务协议 stream 在 startup.cs 之外不起作用

[英].net 5 logging to azure app service protocol stream not working outside startup.cs

i currently have a very basic .NET 5 Blazor Server App running at my azure app service.我目前有一个非常基本的 .NET 5 Blazor 服务器应用程序在我的 azure 应用程序服务上运行。

Deployment works as expected, app is running and i can call my service properly.部署按预期工作,应用程序正在运行,我可以正确调用我的服务。 Now i tried to add logging to azure stream and it worked sometimes, now not anymore for a not known reason.现在我尝试将日志记录添加到 azure stream 并且它有时会起作用,现在由于未知原因不再起作用。 Following is happening in error state:以下发生在错误 state 中:

I have configured logging within Program.cs in CreateHostBuilder我已经在 CreateHostBuilder 的 Program.cs 中配置了日志记录

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    //logging.AddAzureWebAppDiagnostics(); //<== NEVER EVER add this again in .net core as it is implicit called and will cause missing logs!!!: https://wakeupandcode.com/logging-in-asp-net-core/
                    logging.AddConsole();
                    logging.AddDebug();
                })

            .ConfigureServices(serviceCollection => serviceCollection
                .Configure<AzureFileLoggerOptions>(options =>
                {
                    options.FileName = $"{DateTime.UtcNow.Hour.ToString()}_{Assembly.GetExecutingAssembly().GetName().Name}_diagnostics_";
                    options.FileSizeLimit = 50 * 1024;
                    options.RetainedFileCountLimit = 5;
                }))

            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

As you may see i commented AddAzureWebAppDiagnostics out as it is implicit called from framework when deployed to azure, so there is no need to call it explicitly, AND I had this issue short time before, and when i commented it out logging worked fine again.如您所见,我将 AddAzureWebAppDiagnostics 注释掉了,因为它在部署到 azure 时从框架隐式调用,因此无需显式调用它,而且我在不久之前遇到了这个问题,当我将它注释掉时,日志记录再次正常工作。 so i thought this was the problem... it was not!所以我认为这是问题所在......不是!

Now problem occured again, so more details:现在问题再次出现,所以更多细节:

I use this configured logging first in startup.cs我首先在 startup.cs 中使用此配置的日志记录

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
        {
            _logger = logger;
            this._logger.LogPrettyInformation($"Current Environment is: {env.EnvironmentName}");

            if (env.IsDevelopment() || env.IsStaging())
            {
                string envi =  env.IsDevelopment() ? EnvironmentEnum.Development.ToString() : EnvironmentEnum.Staging.ToString();
                this._logger.LogPrettyInformation($"Met condition for: {envi}");

                app.UseDeveloperExceptionPage();
            }
            else if (env.EnvironmentName.Equals(EnvironmentEnum.Debug.ToString()))
            {
                this._logger.LogPrettyInformation($"Met condition for: {EnvironmentEnum.Debug.ToString()}");
                
                app.UseDeveloperExceptionPage();
            }
            else if (env.IsProduction())
            {
                this._logger.LogPrettyInformation($"Met condition for: {EnvironmentEnum.Production.ToString()}");

                app.UseExceptionHandler("/Error");

                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }     

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }

These lines with all that LogPretty-stuff are all working just fine?这些带有所有 LogPretty 内容的行都可以正常工作吗? I can see them at my local debbuging output AND at azure protocol stream too!我也可以在我的本地调试 output 和 azure 协议 stream 中看到它们! Looks good ha?看起来不错哈?

Now I use DI to log from pages and services and stuff, this is the part that is not working any more, but worked from time to time.现在我使用 DI 从页面、服务和其他东西中记录,这是不再工作的部分,但有时会工作。 Now when i call my Counter page as brought up to me by the VS template (WeatherForecastService is the same issue...) I have some logs after i increase the count.现在,当我调用 VS 模板向我提供的计数器页面时(WeatherForecastService 是同样的问题......)在我增加计数后我有一些日志。 But they are only shown in Debug output in my Visual Studio debugging session, NOT in my azure stream.但它们仅显示在我的 Visual Studio 调试 session 中的调试 output 中,而不是我的 azureA223B74CFAFD5C8C2 中。

Any Ideas?有任何想法吗? In short:简而言之:

  • all logs working fine in debug session (output window)所有日志在调试 session (输出窗口)中工作正常
  • logs from startup working fine in debug and in azure stream and of course in filesystem under application as configured启动日志在调试和 azure stream 以及当然在配置的应用程序下的文件系统中工作正常
  • others not, Not in file and not in stream, just in debug output!其他人没有,不在文件中,不在流中,只是在调试输出中!

Method for logging - LogPretty - is not throwing any exception.记录方法 - LogPretty - 没有抛出任何异常。

Thank you guys!感谢你们!

As per your usage of logging in Startup.cs and program.cs is all good.根据您登录 Startup.cs 和 program.cs 的使用情况,一切都很好。

logging.AddDebug();

It gives the debug logging in local.它在本地提供调试日志记录。 Refer here for logging .net 5 application请参阅此处记录 .net 5 应用程序

I am following the below steps to get the log stream information我按照以下步骤获取日志 stream 信息

Enable the filesystem logs on Azure Portal在 Azure 门户上启用filesystem logs

To enable the logs, In Azure portal go to App service -> App Service Logs .要启用日志,在Azure 门户go 到App service -> App Service Logs

Enable the Application Logging (Filesystem) .启用应用程序日志记录(文件系统) Then put the Verbose level to be sure to not miss any log.然后把Verbose级别,确保不会错过任何日志。在此处输入图像描述

Write the configuration code编写配置代码

Use the package Microsoft.Extensions.Logging.AzureAppServices使用 package Microsoft.Extensions.Logging.AzureAppServices

Then, add the following code while you configure your web host:然后,在配置 web 主机时添加以下代码:

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.AzureAppServices;
using Microsoft.Extensions.DependencyInjection;

public class Program
{
    public static void Main(string[] args) => CreateWebHostBuilder(args).Build().Run();
    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
    .ConfigureLogging(logging =>
    {
        logging.ClearProviders();
        // We have to be precise on the logging levels
        logging.AddConsole();
        logging.AddDebug();
        logging.AddAzureWebAppDiagnostics(); // which is not required
    })
    .ConfigureServices(services =>
    {
        services.Configure<AzureFileLoggerOptions>(options =>
        {
            options.FileName = "my-azure-diagnostics-";
            options.FileSizeLimit = 50 * 1024;
            options.RetainedFileCountLimit = 5;
        });
    })
    .UseStartup<Startup>();
}

Use below lines of code in a controller or anywhere else, acquire the logger via IoC and start the logging.在 controller 或其他任何地方使用以下代码行,通过 IoC 获取记录器并开始记录。

private ILogger Logger { get; }
public AwesomeController(ILoggerFactory loggerFactory)
{
    this.Logger = loggerFactory.CreateLogger("AwesomeLogger");
}

[HttpGet]
public void Get()
{
    this.Logger.Debug("DEBUG message. GET enpoint was called.");
    this.Logger.Error("Error message. Something went wrong !");
}

Check the logs via Log Stream (In azure portal go to App Service -> Log Stream )通过日志 Stream 检查日志(在 azure 门户 go 到应用程序服务->日志 ZEAE8362293C054F743A

Refer here参考这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM