c# - 使用 Azure Function V3,如何将现有的 Ilogger 注入到新的类文件中?
问题描述
我使用 VS2019 创建了一个新的 Azure Function,V3,CORE 3.1。它使用一个基本的 HTTPTrigger。我创建了一个新的类文件,并希望将现有的 Ilogger 注入其中。如何做到这一点?我是新手,所以任何帮助将不胜感激。
解决方案
我有一个将日志写入 App Insights 的函数,我使用 ILogger。
您可以在其他服务/帮助程序类中将 ILogger 与依赖注入一起使用。
public interface IExampleClass
{
void ExampleMethod();
}
public class ExampleClass : IExampleClass
{
private readonly ILogger<ExampleClass> _logger;
public ExampleClass(ILogger<ExampleClass> logger)
{
_logger = logger;
}
public void ExampleMethod()
{
_logger.LogInformation("Example info log");
}
}
我在启动文件中启用日志记录并注册 DI。
class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddLogging();
builder.Services.AddTransient<ExampleClass, IExampleClass>();
}
}
可以由主类调用。
public class ThisIsAnAzureFunction
{
private readonly IExampleClass _exampleClass;
public ThisIsAnAzureFunction(IExampleClass exampleClass)
{
_exampleClass = exampleClass;
}
[FunctionName("SomeAzureFunctionName")]
public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log)
{
try
{
//Try some stuff
}
catch (Exception exception)
{
//Log some stuff
log.LogError(exception);
throw;
}
}
}
推荐阅读
- python - 在 Django ORM 中分组?
- adobe-analytics - 仅针对 Adobe Analytics 中的特定细分计算的页面停留时间
- python - 在 Python Pillow 中的图像上写 Unicode 文本?
- ios - 核心数据 NSManagedObject - ObservedObjects 未更新
- linux - 与 docker 容器共享虚拟网络
- kubernetes - 在 Kubernetes 中使用 eBPF 进行配置文件
- selenium - Selenium:try/except - driver.driver.find_element_by_xpath().click - 无法传递“selenium.common.exceptions.NoSuchElementException”
- idris - 如何使用来自 Maybe 的数据作为 Vect 大小变量
- keras - Tensorflow:自定义损失函数以鼓励/限制误报/否定
- reactjs - 从 switch 语句反应返回视图