简体   繁体   English

使用 DI 在 Azure 函数中使用 ILogger

[英]Use ILogger in Azure Function using DI

I am trying a fairly easy thing to do, but somehow I am missing something after all the Microsoft documents and SO posts I've been reading today.我正在尝试做一件相当简单的事情,但不知何故,在我今天阅读的所有 Microsoft 文档和 SO 帖子之后,我遗漏了一些东西。

I want to do some proper logging for my Azure Functions and all over the internet the best practice looks like it's Application Insights, but I've been struggling to get my AI to log my custom logs.我想为我的 Azure Functions 和整个互联网做一些适当的日志记录,最佳实践看起来像是 Application Insights,但我一直在努力让我的 AI 记录我的自定义日志。

Here is my test function, if needed I can create a test project also.这是我的测试功能,如果需要,我也可以创建一个测试项目。

Host.json主机文件

 {
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": false
      },
      "logLevel": {
        "default": "Information",
        "Minerva.Clocking": "Information"
      }
    }
  }
}

Startup.cs启动文件

    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
           
            ServiceProvider serviceProvider = builder.Services.BuildServiceProvider();
            Configurations.StaticConfig = serviceProvider.GetService<IConfiguration>();


            ConfigureServices(builder.Services);
        }

        private static void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<IEmailService, EmailService>();

            services.AddHttpClient();
        }
    }

My test function我的测试功能

namespace Minerva.Clocking.Endpoints
{
    public class LoggingTestFunction
    {
        private readonly IEmailService m_EmailService;
        public LoggingTestFunction(IEmailService emailService)
        {
            m_EmailService = emailService;
        }

        [FunctionName("LoggingTestFunction")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"C# HTTP trigger function processed a request. Execution time: {DateTime.Now}");

        log.LogInformation("Info from function");
        log.LogWarning("Warning from function");
        log.LogError("Error from function");


        m_EmailService.LogSimpleMessage();
        m_EmailService.Foo();


            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }
}

My EmailService我的电子邮件服务

namespace Minerva.Clocking.Services
{
    public class EmailService : IEmailService
        {
            private readonly HttpClient m_httpClient;
            private readonly ILogger<EmailService> m_EmailLogger;
            public EmailService(IHttpClientFactory httpClientFactory, ILogger<EmailService> logger)
            {
                m_httpClient = httpClientFactory.CreateClient();
                m_EmailLogger = logger;
            }
    
            public void LogSimpleMessage()
            {
                m_EmailLogger.LogInformation("This is a information to be seen in azure");
                m_EmailLogger.LogError("This is a error to be seen in azure");
                m_EmailLogger.LogWarning("This is a warning to be seen in azure");
            }



 public void Foo()
        {
            m_EmailLogger.LogInformation("Foo");
            m_Telemetry.TrackTrace("BarLog", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information);
            m_Telemetry.TrackEvent("BarEvent");
        }
    }
}

Whenever I look into the AI logs in azure all I see is the message logged inside the function itself and nothing from my EmailService每当我查看 azure 中的 AI 日志时,我看到的只是函数本身中记录的消息,而我的 EmailService 中什么也没有

在此处输入图片说明

Most likely I am missing something, but I am not sure what, can someone point me to a documentation or something that could allow me to log everything that is inside my Azure Function in AI?很可能我遗漏了一些东西,但我不确定是什么,有人可以指出我的文档或可以让我在 AI 中记录 Azure Function 中的所有内容的东西吗?

I would also like to be able to see the logs in console, but I couldn't find any relevant information about that either on the internet (I know I am a bad searcher).我也希望能够在控制台中看到日志,但我在互联网上找不到任何相关信息(我知道我是一个糟糕的搜索者)。

Thank you谢谢

Edit : Updated the code to include ClientTelemetry.编辑:更新了代码以包含 ClientTelemetry。 The log from telemetry I can see in Azure, but still no logs from ILogger.我可以在 Azure 中看到遥测日志,但仍然没有来自 ILogger 的日志。

I believe the problem is in your host.json.我相信问题出在您的 host.json 中。 Try the following:请尝试以下操作:

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true
      },
      "logLevel": {
        "Minerva.Clocking.Endpoints.LoggingTestFunction": "Information"
      }
    }
  }
} 

source: https://github.com/jeffhollan/functions-csharp-custom-ilogger and https://github.com/Azure/Azure-Functions/issues/1484#issuecomment-594914999来源: https : //github.com/jeffhollan/functions-csharp-custom-iloggerhttps://github.com/Azure/Azure-Functions/issues/1484#issuecomment-594914999

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM