Tech Note

Azure, Office 365, Power Platform, etc... の勉強手記

Azure Functions で Serilog を実装する

azure-functions-startup-serilog

Serilog を実装した Azure Functions プロジェクトのサンプルです

出力イメージ

  • コンソール出力

  • ファイル出力

テンプレートから実装した機能

  • パッケージの追加

    • Serilog.AspNetCore
    • Serilog.Exceptions
  • 以下は必要に応じて

    • Serilog.Exceptions.EntityFrameworkCore
  • DI 機能の追加

  • Startup クラスの追加

[assembly: FunctionsStartup(typeof(Startup))]

namespace FunctionApp4;

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
    }
}
  • Serilog の構成
var logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .MinimumLevel.Override("Worker", LogEventLevel.Warning)
    .MinimumLevel.Override("Host", LogEventLevel.Warning)
    .MinimumLevel.Override("System", LogEventLevel.Error)
    .MinimumLevel.Override("Function", LogEventLevel.Error)
    .MinimumLevel.Override("Azure.Storage.Blobs", LogEventLevel.Error)
    .MinimumLevel.Override("Azure.Core", LogEventLevel.Error)
    .WriteTo.Console()
    .WriteTo.Debug()
    .WriteTo.File(
        $"logs\\{nameof(MyFunctionWithSerilog)}.txt",
        LogEventLevel.Information,
        rollingInterval: RollingInterval.Hour)
    .CreateLogger();
  • Serilog のカスタムログプロバイダーを追加
builder.Services.AddLogging(loggingBuilder =>
{
    loggingBuilder.AddSerilog(logger, true);
});
private readonly ILogger<Function1> _logger;

public Function1(ILogger<Function1> logger)
{
    _logger = logger;
}

GitHub

github.com