【Azure 应用服务】App Service .NET Core项目在Program.cs中自定义添加的logger.LogInformation,部署到App Service上后日志不显示Log Stream中的问题

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: 【Azure 应用服务】App Service .NET Core项目在Program.cs中自定义添加的logger.LogInformation,部署到App Service上后日志不显示Log Stream中的问题

问题描述

在.Net Core 5.0 项目中,添加 Microsoft.Extensions.Logging.AzureAppServicesMicrosoft.Extensions.Logging.Abstractions插件后,需要在构建Host的代码中添加  logging.AddAzureWebAppDiagnostics() 。

return Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging =>
                {
                    //logging.AddConsole();
                    logging.AddAzureWebAppDiagnostics();
                })

然后 初始化Logger对象,添加 Console方式输出日志( var _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger<Program>();

 

全部代码为:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace hellodotnetcore
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
             var _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger<Program>();
            //初始化当前Host实例时候随机生成一个GUID,用于在此后的请求中判断当前时候是否被标记为健康,非健康,回收。
            var instance = Guid.NewGuid();
            //firstFailure来记录第一个失败请求所进入当前实例的时间,firstFailure保存在内存中
            DateTime? firstFailure = null;
            //ILogger _logger = null;
            return Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging =>
                {
                    //logging.AddConsole();
                    logging.AddAzureWebAppDiagnostics();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                webBuilder.Configure(configureApp =>
                configureApp.Run(async context =>
                {
                    _logger.LogInformation("TEST THE SELF LOG INFORMATION...");
                    _logger.LogError("TEST THE SELF LOG ERROR...");
                    _logger.LogDebug("TEST THE SELF LOG Debug...");
                    _logger.LogTrace("TEST THE SELF LOG Trace...");
                    _logger.LogWarning("TEST THE SELF LOG Warning...");//当请求URL为fail时候,认为设置返回状态为500,告诉App Service的Health Check功能,当前实例出现故障。
                    if (firstFailure == null && context.Request.Path.Value.ToLower().Contains("fail"))
                    {
                        firstFailure = DateTime.UtcNow;
                    }
                    if (context.Request.Path.Value.ToLower().Contains("exception"))
                    {
                        throw new Exception("this is custom exception for logging ...");
                    }
                    if (firstFailure != null)
                    {
                        context.Response.StatusCode = 500;
                        context.Response.ContentType = "text/html; charset=utf-8";
                        await context.Response.WriteAsync(
                           $"当前实例的GUID为 {instance}.\n<br>" +
                            $"这个实例最早出现错误的时间是 {firstFailure.Value}. 当前时间为是{DateTime.UtcNow}\n\n<br><br>" +
                            $"根据文档的描述 https://docs.microsoft.com/en-us/azure/app-service/monitor-instances-health-check, 如果一个实例在一直保持unhealthy状态一小时,它将会被一个新实例所取代\n\n<br>" +
                            $"According to https://docs.microsoft.com/en-us/azure/app-service/monitor-instances-health-check, If an instance remains unhealthy for one hour, it will be replaced with new instance.<br>");
                    }
                    else
                    {
                        context.Response.StatusCode = 200;
                        context.Response.ContentType = "text/html; charset=utf-8";
                        await context.Response.WriteAsync($"当前实例的GUID为 {instance}.\n<br>" +
                            $"此实例报告显示一切工作正常.");
                    }
                })));
        }
    }
}

 

在本地通过dotnet run测试发现,访问 http://localhost:5000/ 和 http://localhost:5000/exception 就可以看见在代码中的加入的日志信息,达到期望。

 

但是把代码发布到Azure App Service后,通过Log Stream发现,却没有观察到 _logger 日志:

_logger.LogInformation("TEST THE SELF LOG INFORMATION...");

_logger.LogError("TEST THE SELF LOG ERROR...");

_logger.LogDebug("TEST THE SELF LOG Debug...");

_logger.LogTrace("TEST THE SELF LOG Trace...");

_logger.LogWarning("TEST THE SELF LOG Warning...");

App Service 中查看Docker中运行应用的日志:

 

 

问题解决

这是因为App Service没有启用App Service Logs. 当在门户上启用后,在此查看Log Stream文件信息,就可以看见和本地同样的日志信息:

 

 

 

 

参考资料

为 Azure 应用服务配置 ASP.NET 应用: https://docs.azure.cn/zh-cn/app-service/configure-language-dotnet-framework#access-diagnostic-logs

'ILoggerFactory' does not contain a definition for 'AddConsole': https://stackoverflow.com/questions/58259520/iloggerfactory-does-not-contain-a-definition-for-addconsole

There is a seperate issue at play, previously the signature for AddConsole() expected an ILoggerFactory, that has since changed to an ILoggerBuilder, as hinted at in the error message.

The following it seems is the new way to stand up a new Console logger:

var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
相关文章
|
9天前
【Azure Policy】分享Policy实现对Azure Activity Log导出到Log A workspace中
在Policy Rule部分中,选择资源的类型为 "Microsoft.Resources/subscriptions", 效果使用 DeployIfNotExists (如果不存在,则通过修复任务进行修正。 在 existenceCondition 条件中,如果当前订阅已经启用了 diagnostic setting并且输出日志到同一个Log A workspace,表示满足Policy要求,不需要进行修正。 在 deployment 中,使用了 ARM 模板, 为订阅添加Diagnostic Setting并且所有的日志Category均启用。
|
20天前
|
Kubernetes 数据安全/隐私保护 容器
【Azure APIM】APIM Self-Hosted网关中,添加网关日志以记录请求头信息(Request Header / Response Header)
【Azure APIM】APIM Self-Hosted网关中,添加网关日志以记录请求头信息(Request Header / Response Header)
|
20天前
[Azure Developer]把Azure Function中ILogger对象静态化为静态方法提供日志记录
[Azure Developer]把Azure Function中ILogger对象静态化为静态方法提供日志记录
|
20天前
【Azure Function & Application Insights】在Azure Function的日志中,发现DrainMode mode enabled Traces。它是什么意思呢?
【Azure Function & Application Insights】在Azure Function的日志中,发现DrainMode mode enabled Traces。它是什么意思呢?
|
18天前
|
消息中间件 Kubernetes Kafka
微服务从代码到k8s部署应有尽有系列(十一、日志收集)
微服务从代码到k8s部署应有尽有系列(十一、日志收集)
|
19天前
|
监控 Java Serverless
美团 Flink 大作业部署问题之想在Serverless平台上实时查看Spring Boot应用的日志要怎么操作
美团 Flink 大作业部署问题之想在Serverless平台上实时查看Spring Boot应用的日志要怎么操作
|
20天前
|
存储 大数据 索引
【Azure Contianer Apps】在云上使用容器应用时收集日志遇见延迟问题
【Azure Contianer Apps】在云上使用容器应用时收集日志遇见延迟问题
|
20天前
【Azure Function & Application Insights】调用Function上传和下载文件,有时候遇见大于1MB的文件的日志没有记录在Application Insights中
【Azure Function & Application Insights】调用Function上传和下载文件,有时候遇见大于1MB的文件的日志没有记录在Application Insights中
|
20天前
|
网络安全
【Azure Service Bus】启用诊断日志来获取客户端访问Azure Service Bus的IP地址 [2024-03-26 实验结果失败]
【Azure Service Bus】启用诊断日志来获取客户端访问Azure Service Bus的IP地址 [2024-03-26 实验结果失败]
|
20天前
|
存储
【Azure Log A workspace】Azure上很多应用日志收集到Log A workspace后如何来分别各自的占比呢?
【Azure Log A workspace】Azure上很多应用日志收集到Log A workspace后如何来分别各自的占比呢?