在 Azure 上部署的 .NET Core 2.2 Web 应用中设置 Serilog
如何在 Azure 上部署的 .NET Core 2.2 Web 应用中设置 Serilog
引言
标准的 .NET Core 日志记录功能很好,但它默认情况下不提供将日志记录到文件的功能。我的需求是在开发期间在 Visual Studio 调试窗口中显示应用程序日志消息,并在我的本地 PC 上进行开发时将它们记录到物理文件中,但部署到生产环境后,将消息记录到 Azure 服务器上的物理文件中,并允许在需要时使用 Azure 的“日志流”功能进行流式传输。我还希望能够更改 *appsettings.*.json 文件中的配置选项,以便部署后无需修改代码。
步骤 1:安装以下 NuGet 包
Serilog.AspNetCore
Serilog.Settings.Configuration
Serilog.Sinks.Debug
Serilog.Sinks.File
步骤 2:修改 appsettings.Development.json 文件(配置为写入调试窗口和 “c:\temp” 中的文件)
{
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Fatal",
"System": "Fatal"
}
},
"WriteTo": [
{
"Name": "Debug"
},
{
"Name": "File",
"Args": {
"path": "C:\\Temp\\log.txt",
"fileSizeLimitBytes": "10000",
"rollingInterval": "Day",
"retainedFileCountLimit": "2",
"rollOnFileSizeLimit": "true",
"shared": "true",
"flushToDiskInterval": "00:00:01"
}
}
]
}
}
步骤 3:创建新的或修改现有的 appsettings.Production.json 文件(配置为写入 “d:\home\LogFiles\http\RawLogs” 中的文件)
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Error",
"System": "Error"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "D:\\home\\LogFiles\\http\\RawLogs\\log.txt",
"fileSizeLimitBytes": "1000000",
"rollingInterval": "Day",
"retainedFileCountLimit": "2",
"rollOnFileSizeLimit": "true",
"shared": "true",
"flushToDiskInterval": "00:00:01"
}
}
]
}
}
步骤 4:更新 Program.cs 中的 CreateWebHostBuilder 方法以使用 Serilog 和我们的配置
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseSerilog((context, config) =>
{
config.ReadFrom.Configuration(context.Configuration);
})
.UseStartup<Startup>();
步骤 5:在 Razor 页面中设置一些测试消息,以确认它按预期工作
public class IndexModel : PageModel
{
private readonly ILogger _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
// Log level hierarchy:
// Trace, Debug, Information, Warning, Error, Critical
_logger.LogTrace("IndexModel.OnGet entered (trace)");
_logger.LogDebug("IndexModel.OnGet entered (debug)");
_logger.LogInformation("IndexModel.OnGet entered (info)");
_logger.LogWarning("IndexModel.OnGet entered (warn)");
_logger.LogError("IndexModel.OnGet entered (error)");
_logger.LogCritical("IndexModel.OnGet entered (crit)");
}
}
对那些关心的人来说的 Azure 细节
在 Azure 上,我们需要将“shared”设置为“true”,设置一个较短的刷新磁盘间隔(我选择了每 1 秒),并将日志条目写入“d:\home\LogFiles\http\RawLogs”文件夹,以便“日志流”能够获取日志条目。然后,要查看它们,可以在 Azure 门户的 App 的“诊断日志”选项卡中启用“应用程序日志记录(文件系统)”,并在“日志流”中查看它们。日志文件也会存储在 Azure 服务器上,以便您可以下载它们。