首页 > 解决方案 > 为什么 ILogger.LogTrace 消息没有显示在 v2 Azure Function App 的 func.exe 的控制台窗口中

问题描述

最近在 2018 年 9 月对 Azure Function App 第 2 版进行了更改,我的函数应用代码被重构了。但是,似乎:

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

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

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 表示:

包含最详细消息的日志。这些消息可能包含敏感的应用程序数据。这些消息在默认情况下被禁用,不应在生产环境中启用。

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

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

示例应用程序

函数1.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://docs.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");
        }
    }
}

主机.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"
      }
    }
  }

标签: c#azureloggingazure-functions

解决方案


对于 v2 功能,日志设置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"
    }
  }
}

推荐阅读