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

简介: 【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());

相关实践学习
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
相关文章
|
11月前
|
存储 数据可视化 开发工具
【Application Insights】Application Insights存储的Function App的日志存在"Operation Link" 为空的情况
在将 Azure Functions 升级到 .NET 8 和 Isolated Worker 模式后,Application Insights 的请求日志中 `operation_Link` 字段为空,导致分布式追踪无法正常关联。解决方法包括:确保引用正确的 SDK 包(如 `Microsoft.Azure.Functions.Worker.ApplicationInsights`),正确配置 Application Insights 服务,移除默认日志过滤规则,并使用最新依赖包以支持分布式追踪。通过这些步骤,可恢复端到端事务视图的可视化效果。
215 11
|
存储 监控 API
【Azure App Service】分享使用Python Code获取App Service的服务器日志记录管理配置信息
本文介绍了如何通过Python代码获取App Service中“Web服务器日志记录”的配置状态。借助`azure-mgmt-web` SDK,可通过初始化`WebSiteManagementClient`对象、调用`get_configuration`方法来查看`http_logging_enabled`的值,从而判断日志记录是否启用及存储方式(关闭、存储或文件系统)。示例代码详细展示了实现步骤,并附有执行结果与官方文档参考链接,帮助开发者快速定位和解决问题。
325 22
|
消息中间件 运维 监控
智能运维,由你定义:SAE自定义日志与监控解决方案
通过引入 Sidecar 容器的技术,SAE 为用户提供了更强大的自定义日志与监控解决方案,帮助用户轻松实现日志采集、监控指标收集等功能。未来,SAE 将会支持 istio 多租场景,帮助用户更高效地部署和管理服务网格。
657 51
|
消息中间件 运维 监控
智能运维,由你定义:SAE自定义日志与监控解决方案
SAE(Serverless应用引擎)是阿里云推出的全托管PaaS平台,致力于简化微服务应用开发与管理。为满足用户对可观测性和运维能力的更高需求,SAE引入Sidecar容器技术,实现日志采集、监控指标收集等功能扩展,且无需修改主应用代码。通过共享资源模式和独立资源模式,SAE平衡了资源灵活性与隔离性。同时,提供全链路运维能力,确保应用稳定性。未来,SAE将持续优化,支持更多场景,助力用户高效用云。
|
传感器 人工智能 机器人
D1net阅闻|OpenAI机器人项目招新 或自研传感器
D1net阅闻|OpenAI机器人项目招新 或自研传感器
|
开发框架 安全 .NET
【Azure Developer】.NET Aspire 项目本地调试遇 Grpc.Core.RpcException 异常( Error starting gRPC call ... )
Error starting gRPC call. HttpRequestException: The SSL connection could not be established, see inner exception. AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot
441 12
|
开发框架 前端开发 .NET
一个适用于 .NET 的开源整洁架构项目模板
一个适用于 .NET 的开源整洁架构项目模板
311 26
|
JSON 安全 API
.net 自定义日志类
在.NET中,创建自定义日志类有助于更好地管理日志信息。示例展示了如何创建、配置和使用日志记录功能,包括写入日志文件、设置日志级别、格式化消息等。注意事项涵盖时间戳、日志级别、JSON序列化、线程安全、日志格式、文件处理及示例使用。请根据需求调整代码。
257 13
|
开发框架 网络协议 .NET
C#/.NET/.NET Core优秀项目和框架2024年10月简报
C#/.NET/.NET Core优秀项目和框架2024年10月简报
469 3
|
JSON Java 数据库
SpringBoot项目使用AOP及自定义注解保存操作日志
SpringBoot项目使用AOP及自定义注解保存操作日志
379 1
下一篇
开通oss服务