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/