【问题标题】:Log message from Class library which is used in Azure function来自 Azure 函数中使用的类库的日志消息
【发布时间】:2021-02-02 19:16:28
【问题描述】:

在 Azure 函数中,我可以添加日志,并按预期将其添加到函数日志中。下面是示例代码

[FunctionName("myfunction")]

        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequestMessage req, ILogger log)
        {
           log.LogInformation("HTTP trigger function start");  // This works fine
           MyClass class1 = new MyClass(); // this is from a class library referred in the function
           class1.mymethod()
         }

在 MyClass 方法中,我想以与在 azure 函数中相同的方式记录消息。我尝试在我的类库中创建一个 Ilogger 类型的新日志对象,并使用所需的消息调用 LogInformation 方法。但这不起作用,我在 Microsoft.Extensions.Logging.LoggerExtensions.Log 处收到类似“Value cannot be null. (Parameter 'logger')”的错误

那么我们需要如何在类库中创建新的记录器对象,以便它将消息记录到相同的 Azure 函数日志中。

【问题讨论】:

  • 我不确定我是否理解您的问题。看起来您应该能够将 ILogger 从您的 Azure 函数传递给您实例化的类。你有理由不能这样做吗?
  • 我认为不可能创建一个记录到“Azure 函数日志”的记录器。正如安迪所说,您必须传递log 对象。不是 C# 专家所以不知道,但 App Insights 也收集了 IIRC sysout 和 syserror。

标签: c# azure .net-core azure-functions


【解决方案1】:

首先,将PackageReference for Microsoft.Extensions.Logging.Abstractions* 添加到您的类库项目中。然后,向您的类的构造函数添加一个参数,该参数接受ILogger(或ILogger&lt;YourClass&gt;,如果您打算使用DI)。将记录器存储在一个字段中,然后在需要时使用它。

public class MyClass {
   private readonly ILogger _logger;
   public MyClass(ILogger logger) =>
      _logger = logger ?? throw new ArgumentNullException(nameof(logger));

   public void MyMethod(string name) {
      _logger.LogInformation("Hello {Person}", name);
   }
}

然后,将记录器传递给您的构造函数。

FunctionName("myfunction")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequestMessage req, ILogger log) {
   log.LogInformation("HTTP trigger function start");
   var class1 = new MyClass(log);
   class1.MyMethod("pinkfloydx33");
}

当用户没有提供记录器时,您也可以通过替换NullLogger.Instance(或NullLogger&lt;MyClass&gt;.Instance)来使记录器可选:

public class MyClass {
   private readonly ILogger _logger;
   public MyClass(ILogger logger = null) =>
      _logger = logger ?? NullLogger.Instance;
   //.... 
}

那么您不需要对您的日志记录语句执行任何空值检查。

* 注意最新版本的 Azure Functions 只能在 .NET Core 3.1 上运行。这意味着您只能在类库中引用 Nuget 包的 3.x 行,而不能引用 5.x 版本。虽然它会在技术上编译,但函数 runtime/host 将在运行时抛出 TypeInitializationException。不幸的是,由于 .NET5 不是 LTS,所以在 .NET6 之前不会有新版本的 Azure Functions。如果您想使用 Azure Functions 中的库以及针对 .NET5 的“普通”项目,则必须交叉编译该库。

【讨论】:

    猜你喜欢
    • 2019-04-21
    • 1970-01-01
    • 2011-07-11
    • 2012-02-08
    • 2022-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    相关资源
    最近更新 更多