在Azure webJob中使用ILogger进行DI [英] DI with ILogger in Azure webJob

查看:113
本文介绍了在Azure webJob中使用ILogger进行DI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在.net Framework 4.6中创建了一个天蓝色的webjob项目.我正在尝试使用ILogger实施依赖项注入,并在应用程序见解中记录信息.

I have an azure webjob project created in .net framework 4.6. i am trying to implement dependency injection with ILogger and log the information in application insights.

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

appSettings.json

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

Functions.cs

Functions.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");
    }
}

我也尝试过在ConfigureServices方法中添加以下代码.但是仍然没有运气.

I have also tried adding the below code in ConfigureServices method. 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

推荐答案

我通过vs Web作业模板.net Framework 4.6.1创建了一个Webjob项目,步骤如下:

I created a webjob project from vs web job template, .net framework 4.6.1, steps as below:

步骤1:创建项目

第2步:安装以下软件包:

step 2: install the following package:

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

第3步:在app.config中,添加以下内容:

step 3: in app.config, add following:

第4步:我的program.cs:

step 4: my 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();
            }
        }
    }

第5步:我在Function.cs中的代码:

step 5: my code in 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..........");
        }

        }
    }
}

执行后,日志显示在azure门户中->出现异常:

After execution, the logs are shown in azure portal -> go as Exception:

单击以查看详细信息:

Click it to see details:

这篇关于在Azure webJob中使用ILogger进行DI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆