c# - Azure Functions 中的 Serilog

标签 c# azure dependency-injection azure-functions serilog

Azure Functions 中的每个方法都可以有 Microsoft.Extensions.Logging.ILogger注入(inject)其中进行记录。使用WebJobsStartup通过启动类,您可以使用以下语法更改日志记录以使用 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 中,并将它们注入(inject)到方法中或使用即 builder.Services.AddSingleton<IMyInterface, MyImplementation>(); 的包含方法的类的构造函数中。

但是,我非常希望能够注入(inject)Microsoft.Extensions.Logging.ILogger以同样的方式,但如果我尝试使用 ILogger在构造函数中,我在方法调用期间收到以下错误(因为这是创建类时的错误):

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

那么,有什么方法可以注入(inject) ILogger像这样的类构造函数?

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

}

关于c# - Azure Functions 中的 Serilog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55916750/

相关文章:

c# - 返回 View 内的部分 View

azure - 如何修复 azure wiki 中的 toc 超链接 anchor 滚动位置(当存在重复 anchor 时 - 例如 : sub-topic)?

azure - 部署 Web App Linux 在容器中启动,即使发布模型是代码

c# - Linq 查询在 C# 中返回值而不是设置值(附示例)

c# - 格式化字符串以匹配特定模式

Azure 提供的负载均衡器名称解析

java - 注入(inject)运行时值的更好方法

c# - di 使用 caSTLe windsor 的问题

java - 是否可以在 Dagger 2 中有选择地为组件设置模块?

c# - 将 C# 移植到安卓