我们使用 Serilog(封装在 .NET
ILogger
中)在使用 .NET Core 编写的 Google Cloud 函数以及 Google Cloud 中 Kubernetes 容器中的 ASP.NET Core API 中执行日志记录。当我们尝试添加结构化数据以显示在每个记录事件的 Google jsonPayload
中时,它适用于 ASP.NET Core 服务,但不适用于 .NET Core 功能。
这是我们正在使用的代码。前三批代码是我们如何初始化 Serilog,分别针对 API 和函数,以及它们的共享配置依赖项。在这些示例之后,我们将如何添加应出现在 Google 的 API 和函数的
LogContext
中的 Serilog jsonPayload
信息。在这些示例之后是用于记录的appsettings.json
内容,这是非常标准的。
“我们所期望的”的简短版本是当我们在 Google Cloud Logs Explorer 中查看并检查来自该函数的任何日志记录时,我们的任意 DTO 将在
properties
中的 message
之后显示在 jsonPayload
中。
我们的想法集中在这样一个事实:API 具有与 .NET Core 对象不同的“主机构建器”对象,尽管两个主机构建器都实现了
IHostBuilder
。但这很容易出错。有人告诉我们吗!
是的,我们确实安装了所有规定的 NuGet 包。
初始化代码:API
public static WebApplicationBuilder AddStructuredLoggerToCloudApiService(this WebApplicationBuilder builder)
{
var definition = DefineLoggingSetup(builder.Configuration);
var logger = definition.CreateLogger();
builder.Host.ConfigureLogging(logging => logging.AddSerilog(logger));
// Chainable.
return builder;
}
初始化代码:函数
public static IHostBuilder AddStructuredLoggerToCloudFunction(this IHostBuilder builder, WebHostBuilderContext context)
{
var definition = DefineLoggingSetup(context.Configuration);
var logger = definition.CreateLogger();
builder.ConfigureLogging(logging => logging.AddSerilog(logger));
// Chainable.
return builder;
}
初始化代码:共享配置依赖
private static LoggerConfiguration DefineLoggingSetup(IConfiguration config)
{
var definition = new LoggerConfiguration()
.ReadFrom.Configuration(config) // Scoped to calling code: sinks, message template.
.Enrich.FromLogContext(); // Supports later AddLogData, etc.
return definition;
}
使用
LogContext
public static IDisposable AddLogData<TLogData>(this ILogger _, TLogData data)
{
return LogContext.PushProperty(typeof(TLogData).Name, data, true);
}
在
appsettings.json
中记录配置
"Serilog": {
"Using": [ "Serilog.Sinks.GoogleCloudLogging" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "GoogleCloudLogging",
"Args": {
"projectID": "************",
"restrictedToMinimumLevel": "Information",
"outputTemplate": "****=> {Timestamp:HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"
}
}
]
}
(确切的 GCP 项目 ID 已被编辑。)
万一其他人也出现这个问题,我会在这里发布答案,尽管我讨厌最终不得不在 StackOverflow 中回答我自己的问题。
简短回答: 当您使用 Google Cloud 功能时,您必须设置日志记录以替代不同的预定义方法
ConfigureLogging()
。该方法中的构建器是一个ILoggingBuilder
,默认不规则地命名为logging
,这里的上下文是一个WebHostBuilderContext
。
我们的最终代码如下所示:
logging.AddStructuredLoggerToCloudFunction(context);
AddStructured___()
的定义必须稍作更改才能使用 ILoggingBuilder
,但这是唯一的变化。
仅此而已。