azure - 当依赖注入(inject)和日志记录与 Azure Functions 正常工作时,在没有更改代码的情况下突然开始失败

标签 azure azure-functions

我有一个项目通过构造函数使用依赖项注入(inject),并使用 Azure Function 2.0 从 ASP.NET Core 进行 MS 日志记录,该项目在本地和 Azure 上的 2.0.12333 下运行,现在有以下两个问题:

1) 通过构造函数进行依赖注入(inject)抛出异常,该异常之前是有效的。

2) 日志记录不再写入文本文件,而以前可以正常工作。

下面是演示上述问题 1 的示例代码。

1) 通过构造函数进行依赖注入(inject)抛出异常

下面的异常(exception)是示例代码:

2019-03-15T01:28:45.311 [Error] Executed 'Test' (Failed, Id=6bdb0e8e-2353-4ed2-83ce-2a5288fd124d)
System.InvalidOperationException : Unable to resolve service for type 'ICar' while attempting to activate 'TestFunctions'.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,Boolean isDefaultParameterRequired)
   at lambda_method(Closure ,IServiceProvider ,Object[] )
   at Microsoft.Azure.WebJobs.Host.Executors.DefaultJobActivator.CreateInstance[T](IServiceProvider serviceProvider) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\DefaultJobActivator.cs : 42
   at Microsoft.Azure.WebJobs.Host.Executors.DefaultJobActivator.CreateInstance[T](IFunctionInstanceEx functionInstance) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\DefaultJobActivator.cs : 32
   at Microsoft.Azure.WebJobs.Host.Executors.ActivatorInstanceFactory`1.<>c__DisplayClass1_1.<.ctor>b__0(IFunctionInstanceEx i) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\ActivatorInstanceFactory.cs : 20
   at Microsoft.Azure.WebJobs.Host.Executors.ActivatorInstanceFactory`1.Create(IFunctionInstanceEx functionInstance) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\ActivatorInstanceFactory.cs : 26
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.CreateInstance(IFunctionInstanceEx functionInstance) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs : 44
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ParameterHelper.Initialize() at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs : 845
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsyncCore(IFunctionInstanceEx functionInstance,CancellationToken cancellationToken) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs : 116

示例代码如下:

 public class TestFunctions
    {
        private readonly ICar _car;
        private readonly ILogger _log;
        private const string RouteTemplate = "";

        public TestFunctions(
            ICar car, 
            ILoggerFactory loggerFactor)
        {
            _car = car;
            _log = loggerFactor.CreateLogger<TestFunctions>();

        }

        [FunctionName(nameof(Test))]
        public IActionResult Test(
            [HttpTrigger(AuthorizationLevel.Anonymous,"Get","post", Route = RouteTemplate + nameof(Test))]
            HttpRequest httpRequest, ExecutionContext context)
        {
            _log.LogInformation($"{nameof(Test)} started processing the request.");
            return new ContentResult { StatusCode = 200, Content = $"OK" };
        }

    }

    public interface ICar
    {
        string Name { get; }
    }

    public class Car : ICar
    {
        public string Name { get => "car name"; }
    }

[assembly: WebJobsStartup(typeof(WebJobsStartup))]
    public class WebJobsStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            builder.Services.AddHttpClient();
            builder.Services.AddSingleton<ICar, Car>();
            builder.Services.AddLogging();            


        }
    }

主机.json

{
  "version": "2.0",
  "extensions": {
    "http": {
      "routePrefix": "api/v1"
    }
  },
  "logging": {
    "fileLoggingMode": "always",
    "logLevel": {
      "default": "Information"
    }

  }
}

2) 日志记录不再写入文本文件

当通过构造函数 TestFunctions 进行依赖注入(inject)被删除时,将调用 Test 方法。但是,Test 方法中的日志记录并未将内容写入文件。

再次强调,DI 和日志记录之前都可以正常工作。

 public TestFunctions(
            //ICar car, 
            ILoggerFactory loggerFactor)
        {}

测试方法中的日志信息

_log.LogInformation($"{nameof(Test)} started processing the request.");

Test 方法中的日志记录未将内容写入文件。

2019-03-15T01:34:56.360 [Information] Initializing Host. 2019-03-15T01:34:56.371 [Information] Host initialization: ConsecutiveErrors=0, StartupCount=1 2019-03-15T01:34:56.440 [Information] ApplicationInsightsLoggerOptions {   "SamplingSettings": {
    "EvaluationInterval": "00:00:15",
    "InitialSamplingPercentage": 100.0,
    "MaxSamplingPercentage": 100.0,
    "MaxTelemetryItemsPerSecond": 5.0,
    "MinSamplingPercentage": 0.1,
    "MovingAverageRatio": 0.25,
    "SamplingPercentageDecreaseTimeout": "00:02:00",
    "SamplingPercentageIncreaseTimeout": "00:15:00"   },   "SnapshotConfiguration": null } 2019-03-15T01:34:56.441 [Information] LoggerFilterOptions {   "MinLevel": "None",   "Rules": [
    {
      "ProviderName": null,
      "CategoryName": null,
      "LogLevel": null,
      "Filter": "<AddFilter>b__0"
    },
    {
      "ProviderName": null,
      "CategoryName": null,
      "LogLevel": "Information",
      "Filter": null
    },
    {
      "ProviderName": "Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics.SystemLoggerProvider",
      "CategoryName": null,
      "LogLevel": "None",
      "Filter": null
    },
    {
      "ProviderName": "Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics.SystemLoggerProvider",
      "CategoryName": null,
      "LogLevel": null,
      "Filter": "<AddFilter>b__0"
    },
    {
      "ProviderName": "Microsoft.Azure.WebJobs.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider",
      "CategoryName": null,
      "LogLevel": "Trace",
      "Filter": null
    }   ] } 2019-03-15T01:34:56.441 [Information] LoggerFilterOptions {   "MinLevel": "None",   "Rules": [
    {
      "ProviderName": null,
      "CategoryName": null,
      "LogLevel": null,
      "Filter": "<AddFilter>b__0"
    },
    {
      "ProviderName": null,
      "CategoryName": null,
      "LogLevel": "Information",
      "Filter": null
    },
    {
      "ProviderName": "Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics.SystemLoggerProvider",
      "CategoryName": null,
      "LogLevel": "None",
      "Filter": null
    },
    {
      "ProviderName": "Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics.SystemLoggerProvider",
      "CategoryName": null,
      "LogLevel": null,
      "Filter": "<AddFilter>b__0"
    },
    {
      "ProviderName": "Microsoft.Azure.WebJobs.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider",
      "CategoryName": null,
      "LogLevel": "Trace",
      "Filter": null
    }   ] } 
2019-03-15T01:34:56.441 [Information] FunctionResultAggregatorOptions
{
  "BatchSize": 1000,
  "FlushTimeout": "00:00:30",
  "IsEnabled": true
}
2019-03-15T01:34:56.441 [Information] SingletonOptions
{
  "LockPeriod": "00:00:15",
  "ListenerLockPeriod": "00:00:15",
  "LockAcquisitionTimeout": "10675199.02:48:05.4775807",
  "LockAcquisitionPollingInterval": "00:00:05",
  "ListenerLockRecoveryPollingInterval": "00:01:00"
}
2019-03-15T01:34:56.448 [Information] Starting JobHost
2019-03-15T01:34:56.451 [Information] Starting Host (HostId=My-azureportal, InstanceId=id, Version=2.0.12353.0, ProcessId=5772, AppDomainId=1, InDebugMode=True, InDiagnosticMode=False, FunctionsExtensionVersion=~2)
2019-03-15T01:34:56.488 [Information] Loading functions metadata
2019-03-15T01:34:56.645 [Information] 1 functions loaded
2019-03-15T01:34:56.810 [Information] Generating 1 job function(s)
2019-03-15T01:34:56.868 [Information] Found the following functions:
TestFunctions.Test
2019-03-15T01:34:56.868 [Information] Host initialized (410ms)
2019-03-15T01:34:56.877 [Information] Host started (418ms)
2019-03-15T01:34:56.877 [Information] Job host started
2019-03-15T01:34:57.324 [Information] Executing 'Test' (Reason='This function was programmatically called via the host APIs.', Id=my id)
2019-03-15T01:34:57.370 [Information] Executed 'Test' (Succeeded, Id=my id)
2019-03-15T01:35:02.019 [Information] Host lock lease acquired by instance ID 'id'.

VS 2017

Azure 函数 2.x

最佳答案

要解决本地 Azure Functions 的运行时问题,请参阅 Setting Azure Functions Runtime Version for local dev with Visual Studio 2017

解决方案

当前版本的 Azure Functions Runtime 2.0.12353 会导致此问题。

https://github.com/Azure/azure-functions-host/releases

其他版本(例如 2.0.12342.0)也可以使用

在“功能应用程序设置”下,进行如下设置

FUNCTIONS_EXTENSION_VERSION = 2.0.12342.0

关于azure - 当依赖注入(inject)和日志记录与 Azure Functions 正常工作时,在没有更改代码的情况下突然开始失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55174543/

相关文章:

c# - Azure 应用服务从服务间请求中删除 Jaeger HTTP header

azure - Azure Web 应用程序中的多个站点

c# - 如何实现 Azure 表存储以允许单元测试

azure - 了解 Azure 编排功能的并行化

azure - 使用托管服务标识从数据工厂调用 Azure Function

java - Azure 函数。从 VS Code 调试 java。无法连接到被调试虚拟机

Azure SSIS 包 - 执行 SQL 任务

c# - Azure Keyvault 停止在 IIS 托管站点上工作

c# - 未生成的 Azure Functions C# 输入绑定(bind)是 function.json

azure - 停止 Azure Function 记录 “Executing” 和 “Executed” 消息