use*_*346 6 c# azure azure-application-insights azure-functions microsoft-extensions-logging
我们的函数将所有逻辑委托给另一个类“CreateHandler”,我们在其中通过 DI 使用 ILogger。该函数可以正确记录日志,但 CreateHandler 却不能。在本地,我们验证了它不会登录到控制台,除非我们将类命名空间更改为以“Function”开头的名称。这意味着 FunctionR 或 FunctionS 可以工作,但 RFunction 或 SFunction 不会。我们正在处理该类和服务。显然,我们的服务有一个完全不同的命名空间,我们需要保留该命名空间,同时进行日志记录。如何在不改变命名空间的情况下使类日志生效?
CreateHandler 类(记录正确):
using ExampleProject.Domain.Entities;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace FunctionAnything
{
public class CreateHandler
{
private readonly ILogger<CreateHandler> _logger;
public CreateHandler(
ILogger<CreateHandler> logger)
{
_logger = logger;
}
public async Task Handle(Car car)
{
_logger.LogInformation($"This is logging properly");
}
}
}
Run Code Online (Sandbox Code Playgroud)
CreateHandler 类(不记录日志):
using ExampleProject.Domain.Entities;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace ExampleProject.Functions.Handlers
{
public class CreateHandler
{
private readonly ILogger<CreateHandler> _logger;
public CreateHandler(
ILogger<CreateHandler> logger)
{
_logger = logger;
}
public async Task Handle(Car car)
{
_logger.LogInformation($"This is not logging");
}
}
}
Run Code Online (Sandbox Code Playgroud)
启动:
using ExampleProject.Functions.Handlers;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(ExampleProject.Functions.Startup))]
namespace ExampleProject.Functions
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddSingleton<CreateHandler>();
}
}
}
Run Code Online (Sandbox Code Playgroud)
功能:
using ExampleProject.Domain.Entities;
using ExampleProject.Functions.Handlers;
using ExampleProject.Service.Constants;
using Microsoft.Azure.WebJobs;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace ExampleProject.Functions
{
public class Function
{
private readonly CreateHandler _createHandler;
public Function(
CreateHandler createHandler)
{
_createHandler = createHandler;
}
[FunctionName("Create")]
public async Task Create([QueueTrigger(QueueNames.Create)] Car car)
{
log.LogInformation("I'm logged");
await _createHandler.Handle(car);
}
}
}
Run Code Online (Sandbox Code Playgroud)
本地.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}
Run Code Online (Sandbox Code Playgroud)
主机.json:
{
"version": "2.0",
}
Run Code Online (Sandbox Code Playgroud)
我之前在github上注意到这个问题(如果命名空间不是以Function开头的话),但目前找不到它。
解决办法是,如果命名空间不是以Function开头,则需要添加完整的namespace+class名称。host.json就像下面这样:
{
"version": "2.0",
"logging": {
"logLevel": {
"ExampleProject.Functions.Handlers.CreateHandler": "Information"
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者一般的方式:
"logLevel": { "Default": "Information" }
Run Code Online (Sandbox Code Playgroud)