【发布时间】:2021-06-01 15:35:00
【问题描述】:
我需要将 dotnet5 与 Azure Functions 一起使用,因此按照指南创建新解决方案:https://docs.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide。
这很好用,所以接下来的工作是为控制台和 sql 服务器添加带有接收器的 serilog。
我已经添加了 nuget 包:
- Serilog.AspNetCore v4.1.0
- Serilog.Sinks.MSSqlServer v5.6.0
这里是 Program.Main:
static void Main(string[] args)
{
string EventName = "Main";
var columnOptions = new ColumnOptions
{
AdditionalColumns = new Collection<SqlColumn>
{
new SqlColumn
{ColumnName = "EventName", DataType = SqlDbType.NVarChar, DataLength = 32, NonClusteredIndex = true}
}
};
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft.Azure", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.MSSqlServer(
logEventFormatter: new RenderedCompactJsonFormatter(),
restrictedToMinimumLevel: LogEventLevel.Debug,
connectionString: "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SmsRouter",
sinkOptions: new MSSqlServerSinkOptions
{
TableName = "LogEvents",
AutoCreateSqlTable = true,
},
columnOptions: columnOptions)
.CreateLogger();
try
{
Log.Information("Starting up {EventName}", EventName);
var host = new HostBuilder()
.UseSerilog()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(s =>
{
//services configured here
})
.Build();
host.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application start-up failed");
}
finally
{
Log.CloseAndFlush();
}
}
您可以看到 Log.Information("Starting up {EventName}", EventName); 这行代码有效并记录到控制台和 Sql Server :)
App 启动后会等待 Http 请求 - 如下所示:
[Function("SendSimpleSms")]
public async Task<QueueAndHttpOutputType> RunSimple([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
FunctionContext executionContext)
{
string EventName = "SendSimpleSms";
try
{
Log.Information("Starting: {EventName}", EventName);
我的问题是,这个日志请求“Starting: SendSimpleSms”被记录到控制台窗口而不是 Sql Server。
有人看看我有什么问题吗?
【问题讨论】:
-
启用 Serilog 的自我记录以查看问题所在,例如
Serilog.Debugging.SelfLog.Enable(msg => System.Diagnostics.Debug.WriteLine(msg));或Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg)); -
顺便说一句,Azure 中没有
LocalDB,所以我假设您发布的代码仅用于测试?在生产环境中,您必须使用指向真实数据库的连接字符串,可以是 Azure SQL 或 VM 上的 SQL Server。但两者最终可能比 Log Analytics 或 App Insights 每 MB 更贵 -
是 localdb 用于测试。我正在使用应用程序洞察力,但我发现 5 分钟的延迟令人沮丧。此外,将我的自定义日志条目与来自 Az Func 主机的条目混在一起感觉也不对。
-
SQL Server 接收器也缓冲日志消息。记录和监控是不同的野兽,有不同的要求。日志记录具有大量消息和延迟,监控相反。如果您想要低延迟,您应该使用 Prometheus 接收器或 OpenTelemetry,它专为云环境构建。 ASP.NET Core fully supports OpenTelemetry now,发出 Activity/Span ID,允许您跟踪针对特定请求进行的所有调用
标签: asp.net-core serilog