GTH*_*ten 6 c# dependency-injection serilog azure-functions
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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
我还可以将其他对象添加到DI中,然后使用ie将其注入到方法或包含该方法的类的构造函数中 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");
}
}
Run Code Online (Sandbox Code Playgroud)
请尝试下面的代码,它在我这边工作:
[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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1538 次 |
| 最近记录: |