我正在尝试在 Azure Function v4 项目中用 Serilog 替换 Microsoft.Extensions.Logging。
Serilog 正在使用下面的配置工作,但看起来所有日志条目都是通过 Microsoft.Extensions.Logging “管道传输”的,而不是由 Serilog 写入控制台。 查看输出:
[2024-10-23T13:31:26.843Z] Executing 'Functions.TestTrigger' (Reason='This function was programmatically called via the host APIs.', Id=efe14143-428e-4ac8-a498-1abeae4aa53d)
[2024-10-23T13:31:26.917Z] [15:31:26 INF] Retrieved request
第 1 行由框架记录,第 2 行由我们的代码使用 Serilog 记录。 第 2 行的第二个时间戳是由 Serilog 写入的。
是否可以通过Serilog将所有日志条目直接写入控制台?
此外,如果我将 host.json 中的默认日志级别更改为“调试”以外的任何级别,则不会写入 Serilog 中的任何条目。
我错过了什么?
程序.cs:
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetryWorkerService(x => { x.EnableAdaptiveSampling = false; });
services.ConfigureFunctionsApplicationInsights();
})
.ConfigureLogging(loggerBuilder =>
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console(LogEventLevel.Debug)
.CreateBootstrapLogger();
loggerBuilder.AddSerilog(Log.Logger, true);
})
.UseSerilog((_, sp, loggerCfg) => loggerCfg
.Enrich.FromLogContext()
.WriteTo.Console(LogEventLevel.Debug)
.WriteTo.ApplicationInsights(sp.GetRequiredService<TelemetryClient>(), TelemetryConverter.Traces))
.Build();
host.Run();
主机.json:
{
"version": "2.0",
"logging": {
"logLevel": {
"default": "Debug"
}
}
}
我们使用 NuGet 包中的 Serilog 引导记录器Serilog.AspNetCore。 这允许我们在本地调试时查看消息。 它稍后允许我们更新记录器。 您可以在Nicholas Blumhardt 的博客上阅读有关引导记录器的更多信息。 我们还在 appsettings.json 中设置 Serilog。 您应该能够从包中提取 Microsoft.Extensions.Logging。希望您可以使用我们的配置来帮助您。
使用的 NuGet 包:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateBootstrapLogger(); //https://nblumhardt.com/2020/10/bootstrap-logger/
try
{
Log.Debug("Starting web application.");
var builder = WebApplication.CreateBuilder(args);
IConfigurationRoot configuration;
var configurationBuilder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
configuration = configurationBuilder.Build();
var env = configuration.GetValue(typeof(string), "environmentVariables:ASPNETCORE_ENVIRONMENT")!.ToString();
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
EnvironmentName = env,
});
builder.Host.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
);
var app = builder.Build();
/* Setup App i.e. app.UseAuthentication(); */
app.UseSerilogRequestLogging(options =>
{
// Customize the message template
options.MessageTemplate = "{RequestPath} responded {StatusCode} in {Elapsed}";
// Emit debug-level events instead of the defaults
options.GetLevel = (httpContext, elapsed, ex) => LogEventLevel.Debug;
// Attach additional properties to the request completion event
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
//diagnosticContext.Set("StatusCode", httpContext.Response.StatusCode);
};
});
app.Run();
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.MSSqlServer" ],
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft.AspNetCore": "Warning",
"Microsoft": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "*****",
"sinkOptionsSection": {
"tableName": "logTableName",
"schemaName": "user",
"autoCreateSqlTable": false,
"batchPostingLimit": 1000,
"period": "0.00:00:30"
},
"restrictedToMinimumLevel": "Debug",
"columnOptionsSection": {
"disableTriggers": true,
"clusteredColumnstoreIndex": false,
"primaryKeyColumnName": "Id",
"addStandardColumns": [ "LogEvent" ],
"additionalColumns": [
{
"ColumnName": "EnvironmentUserName",
"DataType": "nvarchar",
"DataLength": 120,
"AllowNull": true
},
{
"ColumnName": "MachineName",
"DataType": "nvarchar",
"DataLength": 120,
"AllowNull": true
},
{
"ColumnName": "ProcessId",
"DataType": "int",
"AllowNull": true
},
{
"ColumnName": "ThreadId",
"DataType": "int",
"AllowNull": true
},
{
"ColumnName": "BatchId",
"DataType": "nvarchar",
"DataLength": 120,
"AllowNull": true
},
{
"ColumnName": "ApplicationName",
"DataType": "nvarchar",
"DataLength": 120,
"AllowNull": true
},
{
"ColumnName": "CorrelationId",
"PropertyName": "ConnectionId",
"DataType": "nvarchar",
"DataLength": 120,
"AllowNull": true
}
],
"id": {
"columnName": "Id",
"nonClusteredIndex": true
},
"message": { "columnName": "Message" },
"messageTemplate": { "columnName": "MessageTemplate" },
"level": {
"columnName": "Level",
"storeAsEnum": false
},
"timeStamp": {
"columnName": "TimeStamp",
"convertToUtc": true
},
"exception": { "columnName": "Exception" },
"properties": {
"columnName": "Properties",
"excludeAdditionalProperties": true,
"dictionaryElementName": "dict",
"itemElementName": "item",
"omitDictionaryContainerElement": false,
"omitSequenceContainerElement": false,
"omitStructureContainerElement": false,
"omitElementIfEmpty": true,
"propertyElementName": "prop",
"rootElementName": "root",
"sequenceElementName": "seq",
"structureElementName": "struct",
"usePropertyKeyAsElementName": false
},
"logEvent": {
"columnName": "LogEvent",
"excludeAdditionalProperties": true,
"excludeStandardColumns": true
}
}
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId", "WithEnvironmentUserName" ],
"Properties": {
"ApplicationName": "My Cool Website"
}
},
"AllowedHosts": "*"
}