无法查看Web应用程序日志:本地及AKS部署后日志定位求助
问题描述
我创建了一个Web应用程序,以下是该应用程序的入口点代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Routing; using Microsoft.Graph.Communications.Common.Telemetry; namespace ProductsApp3 { public class WebApiApplication : System.Web.HttpApplication { private readonly IGraphLogger logger; public WebApiApplication() { this.logger = new GraphLogger(typeof(WebApiApplication).Assembly.GetName().Name, redirectToTrace: true); } protected void Application_Start() { this.logger.Info("WorkerRole has been started"); Console.WriteLine("Sai"); GlobalConfiguration.Configure(WebApiConfig.Register); } } }
但在Visual Studio中运行该应用程序时,无法看到以下语句的输出:
this.logger.Info("WorkerRole has been started"); Console.WriteLine("Sai");
恳请协助说明,在本地环境以及将应用部署到AKS后,该如何查看这些日志信息。
解决方案
本地开发环境(Visual Studio)
查看Console.WriteLine输出
- 若使用IIS Express运行Web API:
- 通过顶部菜单
视图 > 输出打开输出窗口。 - 在输出窗口的下拉菜单中选择IIS Express,即可看到
Console.WriteLine的输出内容。
- 通过顶部菜单
- 若以自托管或控制台应用模式运行:
直接查看Visual Studio的控制台窗口即可。
查看GraphLogger的日志输出
因初始化GraphLogger时设置了redirectToTrace: true,日志会输出到.NET的Trace系统:
- 打开Visual Studio的输出窗口,在下拉菜单中选择调试,就能看到
GraphLogger.Info的日志内容。 - 也可添加
TraceListener将日志输出到文件,在web.config中添加如下配置,日志会写入指定路径的文件:
<system.diagnostics> <trace autoflush="true"> <listeners> <add name="fileListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\Logs\app_trace.log" /> </listeners> </trace> </system.diagnostics>
部署到AKS(Azure Kubernetes Service)后
查看Console.WriteLine和GraphLogger的日志
Kubernetes会收集容器的标准输出(包括Console.WriteLine和默认输出到控制台的日志),可通过以下方式查看:
- 使用
kubectl命令查看Pod日志:- 先获取目标Pod名称:
kubectl get pods - 查看Pod实时日志:
kubectl logs -f <pod-name> - 若应用包含多个容器,需指定容器名:
kubectl logs -f <pod-name> <container-name>
- 先获取目标Pod名称:
- 若配置了Azure Monitor for Containers:
- 在Azure门户的AKS资源页面中,进入监控 > 日志,使用Kusto查询语言检索日志,示例:
ContainerLog | where ContainerName == "<你的容器名>" | where LogEntry contains "WorkerRole has been started" or LogEntry contains "Sai"
- 在Azure门户的AKS资源页面中,进入监控 > 日志,使用Kusto查询语言检索日志,示例:
- 也可在部署时配置日志持久化,比如挂载PVC将日志写入存储卷,或使用ELK Stack等第三方工具集中管理日志。
内容的提问来源于stack exchange,提问作者Sailakshmi
相关产品推荐
相关产品推荐

