【发布时间】:2018-04-10 08:08:51
【问题描述】:
我正在尝试在 azure 中启用应用程序日志。 我有一个虚拟的 Net Core 2 应用程序在 azure 的 appService 中运行。
基本上我的目标是在日志流和应用程序日志文件中查看跟踪消息,但我还没有找到正确的方法。
我在阅读其他帖子时发现的一个挑战是他们假设网络配置已经到位。
【问题讨论】:
标签: c# azure logging asp.net-core-2.0
我正在尝试在 azure 中启用应用程序日志。 我有一个虚拟的 Net Core 2 应用程序在 azure 的 appService 中运行。
基本上我的目标是在日志流和应用程序日志文件中查看跟踪消息,但我还没有找到正确的方法。
我在阅读其他帖子时发现的一个挑战是他们假设网络配置已经到位。
【问题讨论】:
标签: c# azure logging asp.net-core-2.0
ASP.NET Core 2.2 的文档是here。
首先,启用应用程序日志并选择适当的级别:
这可能是您诊断任何问题所需要做的全部工作。但如果您想查看日志消息并查看它们,请安装 Microsoft.Extensions.Logging.AzureAppServices NuGet 包。
然后,配置日志记录:
using Microsoft.Extensions.Logging;
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.AddAzureWebAppDiagnostics();
})
.UseStartup<Startup>();
现在您可以注入和使用 ILogger:
public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
Configuration = configuration;
this.logger = logger;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
logger.LogWarning("Starting up");
【讨论】:
运行 dotnet add package EntityFramework Microsoft.Extensions.Logging.AzureAppServices 为您的项目安装日志记录扩展。
Program.cs 文件供参考:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddAzureWebAppDiagnostics();
})
.UseApplicationInsights()
.UseStartup<Startup>()
.Build();
}
【讨论】:
您需要使用“Microsoft.Extensions.Logging.AzureAppServices”包,然后使用下面的代码为 azure 注册日志记录提供程序。
loggerFactory.AddAzureWebAppDiagnostics(
new AzureAppServicesDiagnosticsSettings
{
OutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss zzz} [{Level}] {RequestId}-{SourceContext}: {Message}{NewLine}{Exception}"
}
);
【讨论】:
您可以从这个blog 得到答案。以下是博客中的sn-p。
在 ASP.NET Core 应用程序中设置日志记录不需要太多代码。 ASP.NET Core 新项目模板已经在 Startup.Configure 方法中使用此代码设置了一些基本的日志记录提供程序:
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
【讨论】: