简体   繁体   English

在 Azure webJob 中使用 ILogger 进行 DI

[英]DI with ILogger in Azure webJob

I have an azure webjob project created in .net framework 4.6.我有一个在 .net framework 4.6 中创建的 azure webjob 项目。 i am trying to implement dependency injection with ILogger and log the information in application insights.我正在尝试使用 ILogger 实现依赖注入并在应用程序洞察中记录信息。

class Program
{
    private static IConfigurationRoot configuration;

    // Please set the following connection strings in app.config for this WebJob to run:
    // AzureWebJobsDashboard and AzureWebJobsStorage
    public static void Main()
    {
        var config = new JobHostConfiguration();

        if (config.IsDevelopment)
        {
            config.UseDevelopmentSettings();
        }
        var builder = new ConfigurationBuilder()
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                      .AddEnvironmentVariables();

        IServiceCollection serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);
        //config.JobActivator = new CustomJobActivator(serviceCollection.BuildServiceProvider());
        config.LoggerFactory = new LoggerFactory()
           .AddApplicationInsights(configuration.GetSection("ApplicationInsights")["InstrumentationKey"], null);
        config.UseTimers();
        var host = new JobHost(config);
        // The following code ensures that the WebJob will be running continuously
        host.RunAndBlock();
    }

    private static void ConfigureServices(IServiceCollection serviceCollection)
    {
        serviceCollection.AddTransient<Functions, Functions>();
        serviceCollection.AddLogging();
    }
}

appSettings.json应用设置.json

{   
    "ApplicationInsights": {
        "InstrumentationKey": "8028437c-888-666-444-2cf3777106a8"
    }
}

Functions.cs函数.cs

public class Functions
{
    private readonly ILogger<Functions> _logger;

    public Functions(ILogger<Functions> logger)
    {
        _logger = logger;
    }

    public void ProcessTimerMessage([TimerTrigger("0 */5 * * * *")]TimerInfo timerInfo, TextWriter log)
    {
        //LOG THIS IN APP INSIGHTS
        _logger.LogError("Error");
    }
}

I have also tried adding the below code in ConfigureServices method.我还尝试在 ConfigureServices 方法中添加以下代码。 But still no luck.但仍然没有运气。

var telemetryClient = new TelemetryClient(new TelemetryConfiguration()
{
       InstrumentationKey = "<< Instrumentation Key >>"
});
serviceCollection.AddSingleton(x => telemetryClient).AddLogging();

Only the trace logs gets logged in app insights whereas the logger object logs doesnot appear.只有跟踪日志会记录在应用洞察中,而记录器对象日志不会出现。 Please help请帮忙

I created a webjob project from vs web job template, .net framework 4.6.1, steps as below:我从vs web job模板,.net framework 4.6.1创建了一个webjob项目,步骤如下:

step 1: create project第一步:创建项目在此处输入图片说明

step 2: install the following package:第 2 步:安装以下软件包:

Install-Package Microsoft.Azure.WebJobs -version 2.2.0
Install-Package Microsoft.Extensions.Logging -version 2.0.1
Install-Package Microsoft.Extensions.Logging.Console -version 2.0.1
Install-Package Microsoft.Azure.WebJobs.Logging.ApplicationInsights -version 2.2.0
Install-Package System.Configuration.ConfigurationManager -version 4.4.1

step 3: in app.config, add following:第 3 步:在 app.config 中,添加以下内容: 在此处输入图片说明

step 4: my program.cs:第 4 步:我的 program.cs:

  using Microsoft.Azure.WebJobs;
  using Microsoft.Extensions.Logging;
  using System.Configuration;

    namespace WebJob7
    {

        class Program
        {

            static void Main()
            {
                var config = new JobHostConfiguration();
                var instrumentationKey =
                   ConfigurationManager.AppSettings["APPINSIGHTS_INSTRUMENTATIONKEY"];

                config.DashboardConnectionString = "";

                config.LoggerFactory = new LoggerFactory()
                    .AddApplicationInsights(instrumentationKey, null)
                    .AddConsole();

                if (config.IsDevelopment)
                {
                    config.UseDevelopmentSettings();
                }

                var host = new JobHost(config);

                host.RunAndBlock();
            }
        }
    }

step 5: my code in Function.cs:第 5 步:我在 Function.cs 中的代码:

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;

namespace WebJob7
{
    public class Functions
    {
        // This function will get triggered/executed when a new message is written 
        // on an Azure Queue called queue.
        public static void ProcessQueueMessage([QueueTrigger("queue")] string message, ILogger logger)
        {
        //you can directly use this line of code.
        //logger.LogError(new Exception(),"it is a test error...");

        //or use the following code
        try
        {
            int i = int.Parse("123er");
        }
        catch(Exception ex)
        {
            logger.LogError(ex,"it's a exception here 0927..........");
        }

        }
    }
}

After execution, the logs are shown in azure portal -> go as Exception:执行后,日志显示在 azure 门户中 -> go as Exception: 在此处输入图片说明

Click it to see details:点击查看详情: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM