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
{
"ApplicationInsights": {
"InstrumentationKey": "8028437c-888-666-444-2cf3777106a8"
}
}
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");
}
}
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
I created a webjob project from vs web job template, .net framework 4.6.1, steps as below:
step 1: create project
step 2: install the following package:
step 3: in app.config, add following:
step 4: my program.cs:
step 5: my code in Function.cs:
After execution, the logs are shown in azure portal -> go as Exception:
Click it to see details: