c# - 为什么 v2 Azure Function App 的 func.exe 的控制台窗口中不显示 ILogger.LogTrace 消息

标签 c# azure logging azure-functions

随着 2018 年 9 月对 Azure Function App 版本 2 的最新更改,我的函数应用代码进行了重构。然而,似乎:

  • LogTrace() 消息不再显示在控制台窗口中(我怀疑 Application Insights),并且
  • host.json 中的categoryLevels 似乎没有得到尊重。

下面的示例应用程序在调用LogWithILogger()时重复出现了该问题。另外两点:

(1) 我注意到默认过滤器跟踪级别似乎是硬编码的。是否可以添加另一个 Filter 以允许 LogTrace() 工作,或者应该不再使用 LogTrace()?如果可以添加另一个过滤器,如何将必要的对象注入(inject)到函数应用程序中以允许这样做?

public static void Microsoft.Extensions.Logging.AddDefaultWebJobsFilter(this ILoggingBuilder builder)
{
    builder.SetMinimumLevel(LogLevel.None);
    builder.AddFilter((c,l) => Filter(c, l, LogLevel.Information));
}

(2) LogLevel 周围的 Intellisense 指示:

  • LogLevel.Trace = 0

包含最详细消息的日志。这些消息可能包含敏感的应用程序数据。这些消息默认处于禁用状态,并且永远不应在生产环境中启用。

我希望 LogTrace 可以在调试时用于控制台窗口 - 并且由类别级别设置控制。

那么,在使用 ILogger 为 V2 Function 应用程序编写跟踪消息时应该做什么?谢谢您的建议!

示例应用程序

Function1.cs

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.WebJobs.Description;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;

namespace FunctionAppTestLogging
{
    [AttributeUsage(AttributeTargets.Parameter)]
    [Binding]
    public class InjectAttribute : Attribute
    {
        public InjectAttribute(Type type)
        {
            Type = type;
        }
        public Type Type { get; }
    }

    public class WebJobsExtensionStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder webjobsBuilder)
        {

            webjobsBuilder.Services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace).AddFilter("Function", LogLevel.Trace));
            ServiceCollection serviceCollection =  (ServiceCollection) webjobsBuilder.Services;
            IServiceProvider serviceProvider = webjobsBuilder.Services.BuildServiceProvider();

            // webjobsBuilder.Services.AddLogging();
            //  webjobsBuilder.Services.AddSingleton(new LoggerFactory());
            // loggerFactory.AddApplicationInsights(serviceProvider, Extensions.Logging.LogLevel.Information);
        }
    }

    public static class Function1
    {
        private static string _configuredLoggingLevel;

        [FunctionName("Function1")]
        public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, ILogger log, ExecutionContext context) // , [Inject(typeof(ILoggerFactory))] ILoggerFactory loggerFactory) //  , [Inject(typeof(ILoggingBuilder))] ILoggingBuilder loggingBuilder)
        {
            LogWithILogger(log);
            LogWithSeriLog();
            SetupLocalLoggingConfiguration(context, log);
            LogWithWrappedILogger(log);

            return await RunStandardFunctionCode(req);
        }

        private static void SetupLocalLoggingConfiguration(ExecutionContext context, ILogger log)
        {
            var config = new ConfigurationBuilder()
                            .SetBasePath(context.FunctionAppDirectory)
                            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                            .AddEnvironmentVariables()
                            .Build();

            // Access AppSettings when debugging locally.
            string loggingLevel = config["LoggingLevel"];  // This needs to be set in the Azure Application Settings for it to work in the cloud.
            _configuredLoggingLevel = loggingLevel;
        }

        private static void LogWithWrappedILogger(ILogger log)
        {
            LogWithWrappedILoggerHelper("This is Critical information from WrappedILogger", LogLevel.Critical, log);
            LogWithWrappedILoggerHelper("This is Error information from WrappedILogger", LogLevel.Error, log);
            LogWithWrappedILoggerHelper("This is Information information from WrappedILogger", LogLevel.Information, log);
            LogWithWrappedILoggerHelper("This is Debug information from WrappedILogger", LogLevel.Debug, log);
            LogWithWrappedILoggerHelper("This is TRACE information from WrappedILogger", LogLevel.Trace, log);
        }

        private static void LogWithWrappedILoggerHelper(string message, LogLevel messageLogLevel, ILogger log)
        {
            // This works as expected - Is the host.json logger section not being respected?
            Enum.TryParse(_configuredLoggingLevel, out LogLevel logLevel);
            if (messageLogLevel >= logLevel)
            {
                log.LogInformation(message);
            }
        }

        private static void LogWithILogger(ILogger log)
        {
            var logger = log;
            // Microsoft.Extensions.Logging.Logger _logger = logger; // Logger is protected - so not accessible.

            log.LogCritical("This is critical information!!!");
            log.LogDebug("This is debug information!!!");
            log.LogError("This is error information!!!");
            log.LogInformation("This is information!!!");
            log.LogWarning("This is warning information!!!");

            log.LogTrace("This is TRACE information!! from LogTrace");
            log.Log(LogLevel.Trace, "This is TRACE information from Log", null);
        }

        private static void LogWithSeriLog()
        {
            // Code using the Serilog.Sinks.AzureTableStorage package per https://learn.microsoft.com/en-us/sandbox/functions-recipes/logging?tabs=csharp
            /*
            var serilog = new LoggerConfiguration()
            .WriteTo.AzureTableStorage(connectionString, storageTableName: tableName, restrictedToMinimumLevel: LogEventLevel.Verbose)
            .CreateLogger();
            log.Debug("Here is a debug message {message}", "with some structured content");
            log.Verbose("Here is a verbose log message");
            log.Warning("Here is a warning log message");
            log.Error("Here is an error log message");
            */
        }

        private static async Task<IActionResult> RunStandardFunctionCode(HttpRequest req)
        {
            string name = req.Query["name"];
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
    }
}

host.json

  {
  "version": "2.0",
  // The Azure Function App DOES appear to read from host.json even when debugging locally thru VS, since it complains if you do not use a valid level.
  "logger": {
    "categoryFilter": {
      "defaultLevel": "Trace", // Trace, Information, Error
      "categoryLevels": {
        "Function": "Trace"
      }
    }
  }

最佳答案

对于 v2 函数,log setting host.json 中的格式不同。

{
  "version": "2.0",
  "logging": {
    "fileLoggingMode": "debugOnly",
    "logLevel": {
      // For specific function
      "Function.Function1": "Trace",
      // For all functions
      "Function":"Trace",
      // Default settings, e.g. for host 
      "default": "Trace"
    }
  }
}

关于c# - 为什么 v2 Azure Function App 的 func.exe 的控制台窗口中不显示 ILogger.LogTrace 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52692236/

相关文章:

c# - 从 Uri 获取单个查询参数

c# - 当字段依赖于另一个字段时通知属性更改的最佳方法

php - 从 Azure Active Directory 验证 JWT

asynchronous - 从 Azure 表结构读取 N 个实体的最有效方法是什么

c# - Task.WaitAll 不等待其他异步方法

c# - 在 C# 中使用图片代替矩形

azure - 如何管理 Azure Durable Functions 的执行历史记录

linux - bash 输入/输出到日志文件

java.util.logging.Logger吞咽日志

r - 如何在 RStudio 服务器中同时将输出保存到控制台和文件?