问题描述
Azure Functions中的每个方法都可以将Microsoft.Extensions.Logging.ILogger
插入其中以进行日志记录.将WebJobsStartup
与启动类一起使用,您可以使用以下语法将日志记录更改为使用Serilog:
Each method in Azure Functions can have a Microsoft.Extensions.Logging.ILogger
injected into it for logging. Using WebJobsStartup
with a startup class you can change the logging to use Serilog using the following syntax:
[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>();
I can also add other objects to the DI and inject them either into the methods or into the constructor for the class containing the methods using i.e. builder.Services.AddSingleton<IMyInterface, MyImplementation>();
但是,我非常希望能够以相同的方式注入Microsoft.Extensions.Logging.ILogger
,但是如果我尝试在构造函数中使用ILogger
,则在方法调用期间会出现以下错误(因为那是当类已创建):
However, I would very much like to be able to inject the Microsoft.Extensions.Logging.ILogger
in the same way, but if I try to use the ILogger
in the constructor I get the following error during method invokation (as that's when the class is created):
那么,有什么方法可以将ILogger
注入这样的类构造函数中吗?
So, is there any way of injecting the ILogger
into a class constructor like this?
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");
}
}
推荐答案
请尝试以下代码,它对我有效:
Please try the code below, it works at my side:
[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");
}
}
}
这篇关于Azure Functions中的Serilog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!