Azure Functions - ILogger 跨类记录

CKe*_*ook 4 .net logging azure azure-functions

在 Azure 函数中,run 方法创建一个 ILogger,在我的主类中,我可以用它来记录错误和信息,但是,我使用帮助程序类来运行我的 Graph API 和 Cosmos DB 查询。

在单独的类中记录错误和信息的最佳方法是什么?我应该在所有类或方法中传递日志吗?或者是否有更好的方法使 ILogger 在运行时可供所有类使用?

public class AzureFunction
{
    public Task Run([TimerTrigger("0 0 1 * * *")] TimerInfo myTimer, ILogger log)
    {
        log.LogInformation("This message logs correctly");
        GraphHelper graphHelper = new GraphHelper();
        graphHelper.GetGraphData();
    }
}
 
public class GraphHelper
{
    public void GetGraphData()
    {
        try 
        {
            asyncTask() 
        }
        catch (Exception ex) 
        {
            log.LogInformation($"{ex.Message} - How can I log this without passing ILogger to every class or method?");
        }
    }
}
     
Run Code Online (Sandbox Code Playgroud)

Thi*_*dio 6

正确的方法(恕我直言)是通过依赖注入。

using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace FunctionApp1
{
   public class HelperClass : IHelperClass
    {
        private static ILogger<IHelperClass> _logger;
        public HelperClass(ILogger<IHelperClass> logger)
        {

            _logger = logger;
        }
        public void Dowork()
        {
            _logger.LogInformation("Dowork: Execution Started");
            /* rest of the functionality below
                .....
                .....
            */
            _logger.LogInformation("Dowork: Execution Completed");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

主机.json

{
    "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingExcludedTypes": "Request",
      "samplingSettings": {
        "isEnabled": true
      }
    },
    "logLevel": {
      "FunctionApp1.HelperClass": "Information"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

助手类

using System;
using System.Collections.Generic;
using System.Text;

namespace FunctionApp1
{
    public interface IHelperClass
    {
        void Dowork();
    }
}
Run Code Online (Sandbox Code Playgroud)

主功能

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

namespace FunctionApp1
{
    public class MainFunction // Ensure class is not static (which comes by default)
    {
        private IHelperClass _helper;
     
        public MainFunction(IHelperClass helper)
        {
            _helper = helper;
        }

        [FunctionName("MainFunction")]
        public void Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
            // call helper 
            _helper.Dowork();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

启动.cs

using Microsoft.Azure.Functions.Extensions.DependencyInjection; // install nuget - "Microsoft.Azure.Functions.Extensions"
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

[assembly: FunctionsStartup(typeof(FunctionApp1.Startup))]

namespace FunctionApp1
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {           
            builder.Services.AddSingleton<IHelperClass,HelperClass>();            

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

完整示例可以在https://gist.github.com/nareshnagpal06/82c6b4df2a987087425c32adb58312c2上找到