Azure Functions 中的 Serilog

Serilog in Azure Functions

Azure Functions 中的每个方法都可以有一个 Microsoft.Extensions.Logging.ILogger 注入其中用于日志记录。将 WebJobsStartup 与启动 class 一起使用,您可以使用以下语法将日志记录更改为使用 Serilog:

[assembly: WebJobsStartup(typeof(Startup))]
namespace MyFuncApp {
    public class Startup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            builder.Services.AddLogging(
                lb => lb.ClearProviders()
                    .AddSerilog(
                        new LoggerConfiguration()
                            .Enrich.FromLogContext()
                            .WriteTo.Console()
                            .WriteTo.File(@"C:\Temp\MyFuncApp.log")
                            .CreateLogger(),
                        true));
        }
    }
}

我还可以将其他对象添加到 DI,并将它们注入方法或 class 的构造函数中,其中包含使用 builder.Services.AddSingleton<IMyInterface, MyImplementation>();

的方法

但是,我非常希望能够以相同的方式注入 Microsoft.Extensions.Logging.ILogger,但是如果我尝试在构造函数中使用 ILogger,我会在方法中遇到以下错误调用(因为那是创建 class 的时候):

Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'MyFuncApp.MyFunctions'.

那么,有没有办法像这样将 ILogger 注入到 class 构造函数中?

public class MyFunctions
{
    private IMyInterface _myImpl;
    private ILogger _log;

    public MyFunctions(
        IMyInterface myImplememtation, // This works
        ILogger log) // This does not
    {
        _myImpl = myImplementation;
        _log = log;
        _log.LogInformation("Class constructed");
    }

    public async Task<IActionResult> Function1([HttpTrigger() ... ) {
        _log.LogInformation("Function1 invoked");
    }
}

请尝试下面的代码,它在我这边有效:

    [assembly: WebJobsStartup(typeof(Startup))]
    namespace MyApp
 {
        public class Startup : IWebJobsStartup
        {
            public void Configure(IWebJobsBuilder builder)
            {
                //other code

                builder.Services.AddLogging();
            }
        }



    public class Functions
    {
        //other code
        private ILogger _log;

        public Functions(ILoggerFactory loggerFactory)
        {
            _log = loggerFactory.CreateLogger<Functions>();
        }

        [FunctionName("Token")]
        public async Task<IActionResult> Function1(
            [HttpTrigger()]...)
        {
               _log.LogInformation("Function1 invoked");
        }
    }

}

可以通过使用包 Anotar.Serilog.Fody (and any other Anotar 包来进一步简化必要的设置)

您需要在 Startup class 中完全相同地设置 Serilog。

但是,使用 Fody 包你可以完全摆脱注入的记录器

using Anotar.Serilog;

public class Functions
{
    [FunctionName("Token")]
    public async Task<IActionResult> Function1(
        [HttpTrigger()]...)
    {
        // static calls to the LogTo class
        // get translated into proper Serilog code during build
        LogTo.Information("Function1 invoked");
    }
}

使用 AzureFunctions v3,您在问题中概述的模式有效 out-of-the 框。