为什么不在vunc Azure功能应用程序的func.exe控制台窗口中显示ILogger.LogTrace消息

问题描述 投票:1回答:1

随着最近对2018年9月Azure功能应用程序版本2的更改,我的功能应用程序代码被重构。但是,似乎:

  • LogTrace()消息不再显示在控制台窗口中(我怀疑Application Insights),以及
  • host.json中的categoryLevels似乎不受尊重。

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

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

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用于控制台窗口 - 并且可以通过categoryLevel设置进行控制。

那么,在使用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://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");
        }
    }
}

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"
      }
    }
  }
c# azure logging azure-functions
1个回答
1
投票

对于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"
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.