Azure函数在使用appsettings.json时无法初始化Serilog接收器

3lxsmp7m  于 2022-11-17  发布在  其他
关注(0)|答案(4)|浏览(146)

我创建了一个简单的Azure函数,目的是使用Serililog记录到Azure Blob存储。
当对Serilog接收器使用内联配置时,它工作得非常好,接收器被创建,Serilog很高兴地写入Blob存储。

此方法有效:

Log.Logger = new LoggerConfiguration()
   .WriteTo.AzureBlobStorage(
           "STORAGEACCOUNT CONNECTION STRING", // <-- inline config
           LogEventLevel.Information,
           null,
           "{yyyy}/{MM}/{dd}/MyLogFile.txt")
   .CreateLogger();

问题是,我想通过appsettings.json配置这一切,但当我尝试这一点(无论是在模拟器和云本地运行),它无法绑定接收器设置,因此它无法登录到博客存储。
如果我进行调试,我可以看到配置值 * 正按预期加载到configuration对象 * 中,但它们 * 没有 * 应用到日志记录配置中。

这不起作用:

Log.Logger = new LoggerConfiguration()
   .ReadFrom.Configuration(configuration)
   .CreateLogger();

appsettings.json在此程式码片段中:

{

  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Information"
      }
    },
    "WriteTo": [{
        "Name": "AzureBlobStorage",
        "Args": {
          "connectionString": " --- REPLACE WITH STORAGEACCOUNT BLOB CONNECTION STRING --- ",
          "formatter": "Serilog.Formatting.Compact.RenderedCompactJsonFormatter, Serilog.Formatting.Compact",
          "storageFileName": "{yyyy}/{MM}/{dd}/MyLogFile.txt",
          "retainedFileCountLimit": 31
        }
      }

    ],
    "Properties": {
      "Application": "int-test-logging",
      "Environment": "int"
    }
  }

}

我不知道我做错了什么,但如果能得到任何帮助,我将不胜感激。下面的github repo包含了实现上述两种方法的代码,并重现了这种行为。https://github.com/oneiltomlinson/AzureFunctionsLogging

guicsvcw

guicsvcw1#

只需添加

"Using": [ "Serilog.Sinks.AzureBlobStorage" ] //under Serilog Config

而且一定会成功!
工作配置

{
    "Serilog": {
        "Using": [
            "Serilog.Sinks.AzureBlobStorage"
        ],
        "MinimumLevel": {
            "Default": "Information",
            "Override": {
                "Microsoft": "Information"
            }
        },
        "WriteTo": [
            {
                "Name": "AzureBlobStorage",
                "Args": {
                    "connectionString": " --- REPLACE WITH STORAGEACCOUNT BLOB CONNECTION STRING --- ",
                    "formatter": "Serilog.Formatting.Compact.RenderedCompactJsonFormatter, Serilog.Formatting.Compact",
                    "storageFileName": "{yyyy}/{MM}/{dd}/MyLogFile.txt",
                    "retainedFileCountLimit": 31
                }
            }
        ],
        "Properties": {
            "Application": "int-test-logging",
            "Environment": "int"
        }
    }
}
eblbsuwk

eblbsuwk2#

我也遇到了同样的问题,即使对使用过的接收器进行了所有必要的“使用”,也没有任何变化。这是我的配置文件(只是关于Serilog部分):

"Serilog": {
    "Using": [
      "Serilog.Sinks.RollingFile",
      "Serilog.Sinks.AzureTableStorage"
    ],
    "MinimumLevel": "Information",
    "Override": {
      "Microsoft": "Warning",
      "Microsoft.EntityFrameworkCore": "Information"
    },
    "WriteTo": [
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "MinimumLevel": "Information",
            "WriteTo": [
              {
                "Name": "Console",
                "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{Level:u3}] [TID:{ThreadId}] - {Message:lj}{NewLine}{Exception}"
              },
              {
                "Name": "Debug",
                "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{Level:u3}] [TID:{ThreadId}] - {Message:lj}{NewLine}{Exception}"
              },
              {
                "Name": "AzureTableStorage",
                "Args": {
                  "storageTableName": "HeroFunctionsLogs",
                  "connectionString": "DefaultEndpointsProtocol=https;AccountName=herobugari;AccountKey=NYJcdoCg9mQxqbQaTUdIxOHYQGdcKAwMsuWwzDub29UweHR1c+wd6Sh3IDQNB+eCx3DAe/ccobxu67sJvqQB5g==",
                  "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{Level:u3}] [TID:{ThreadId}] - {Message:lj}{NewLine}{Exception}",
                  "restrictedToMinimumLevel": "Information",
                  "writeInBatches": true,
                  "batchPostingLimit": 100
                }
              },
              {
                "Name": "RollingFile",
                "Args": {
                  "pathFormat": "logs\\Bulgari.Hero.Functions.log",
                  "retainedFileCountLimit": 10,
                  "buffered": true,
                  "flushToDiskInterval": 5,
                  "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{Level:u3}] [TID:{ThreadId}] - {Message:lj}{NewLine}{Exception}"
                }
              }
            ],
            "Filter": [
              {
                "Name": "ByExcludingOnly",
                "Args": {
                  "expression": "SourceContext like '%Microsoft.EntityFrameworkCore%'"
                }
              }
            ]
          }
        }
      }
    ]
  }

下面是Startup.cs代码,它显示并尝试使用它:

var config = new ConfigurationBuilder()
            .SetBasePath(Environment.CurrentDirectory)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables().Build();
    // Registering Serilog provider
    logger = new LoggerConfiguration()
        //.WriteTo.Console()
        //.WriteTo.File("logs\\herofunctions.log", rollingInterval: RollingInterval.Day)
        .ReadFrom.Configuration(config)
        .CreateLogger();
    builder.Services.AddLogging(lb => lb.AddSerilog(logger));

记录器对象没有注册“接收器”,因为它发生在问题中。

aij0ehis

aij0ehis3#

我在这里通过在local.settings.json中添加条目解决了完全相同的问题。

"Serilog:Using:0": "Serilog.Sinks.Console",
"Serilog:MinimumLevel": "Information",
"Serilog:Override:Microsoft": "Warning",
"Serilog:Override:System": "Warning",
"Serilog:WriteTo:Console:Name": "Console"

然后在StartUp.cs中:

var provider = builder.Services.BuildServiceProvider();
var config = provider.GetRequiredService<IConfiguration>();
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(config).CreateLogger();

则函数:

public class TestFunction
{
    private readonly ILogger _logger;
    public TestFunction()
    {
        _logger = Log.Logger;
    }

    [FunctionName("TestFunction")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req)
    {
        _logger.Information("Hello");
        return new OkResult();
    }
}

}
我可以看到注册的配置条目和记录的条目!

ndasle7k

ndasle7k4#

要写入SQL Server,我必须添加:

"Using": [
  "Serilog.Sinks.MSSqlServer"
],

相关问题