【发布时间】:2019-04-30 08:25:46
【问题描述】:
Azure Functions 中的每个方法都可以将Microsoft.Extensions.Logging.ILogger 注入其中以进行日志记录。将 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 中,并将它们注入方法或包含使用方法的类的构造函数中,例如 builder.Services.AddSingleton<IMyInterface, MyImplementation>();
但是,我非常希望能够以相同的方式注入 Microsoft.Extensions.Logging.ILogger,但如果我尝试在构造函数中使用 ILogger,我会在方法调用期间收到以下错误(因为那是类已创建):
Microsoft.Extensions.DependencyInjection.Abstractions:尝试激活“MyFuncApp.MyFunctions”时,无法解析“Microsoft.Extensions.Logging.ILogger”类型的服务。
那么,有没有办法将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");
}
}
【问题讨论】:
标签: c# azure dependency-injection azure-functions serilog