【问题标题】:Serilog not logging from queue triggered azure functionSerilog 未从队列中记录触发的 azure 函数
【发布时间】:2023-04-01 18:06:06
【问题描述】:

我需要将 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:

{
    string EventName = "Main";
    
    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,
                    })
                .CreateLogger();
    Serilog.Debugging.SelfLog.Enable(Console.Error);

    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();
    }
}

FunctionApp 的第一个触发器是一个 Http 请求,如下所示:

[Function("SendSimpleSms")]
    public async Task<QueueAndHttpOutputType> RunSimple([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
        FunctionContext executionContext)
    {
        HttpResponseData httpResponse;
        SmsOrder coreSmsOrder = new SmsOrder();
        string EventName = "SendSimpleSms";
        string CorrelationId = executionContext.FunctionId;
        try
        {
            Log.Information("Starting: {EventName}", EventName);

此处的 Log.Information 调用效果很好,并且将日志写入控制台和 Sql。

“SendSimpleSms”函数然后将消息排队等待由以下函数收集 - 在与“SendSimpleSms”相同的应用程序中运行:

[Function("QueueOrchestration")]
    public async Task Execute([QueueTrigger("%SendSmsQueueName%")] SmsOrder smsOrder, FunctionContext executionContext)
    {
        Log.Information("Will this log?");
        Log.CloseAndFlush();

这一次,控制台或 Sql 中没有记录任何内容。

任何想法为什么当一个函数由 http 触发而不是从队列触发时日志记录会起作用?

【问题讨论】:

    标签: azure-functions serilog


    【解决方案1】:

    仍在使用 Serilog(并受益于 Sql Server Sink),但我已切换到使用注入构造函数的 ILogger 而不是全局 Log 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 2021-03-01
      • 2018-03-26
      • 1970-01-01
      • 2021-07-07
      相关资源
      最近更新 更多