I am building a Worker Service as Windows Service. I use EventLog
for logging. I also want to add ApplicationInsights
to log the events. I follow this article https://learn.microsoft.com/en-us/azure/azure-monitor/app/worker-service , install the SDK using Nuget and setup everything as requested. Here is my program.cs
configuration.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
services.AddApplicationInsightsTelemetryWorkerService();
services.CustomeDependencyInjection();
})
.UseWindowsService()
.ConfigureLogging(logging =>
{
logging.AddEventLog(eventLogSetting =>
{
eventLogSetting.LogName = "MyTestEventLog";
eventLogSetting.SourceName = "MyTestEventApp";
});
});
Here is the appsetting.json
file
{
"ApplicationInsights": {
"InstrumentationKey": "bd******-****-****-****-***********b"
},
Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information"
},
"EventLog": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
}
Here is an logging example in the worker.cs
file
public Worker(ILogger<Worker> logger, TelemetryClient tc)
{
_logger = logger;
this.tc = tc;
}
public Task StartAsync(CancellationToken cancellationToken)
{
this._logger.LogInformation("In Start");
using (tc.StartOperation<RequestTelemetry>("Operation"))
{
/**
my service starting code
**/
this._logger.LogInformation("Service is being started");
tc.TrackEvent("Worker service starting operation completed.");
}
this._logger.LogInformation( "Service Started");
return Task.CompletedTask;
}
When I run the application, I can see a customEvent
. I can also see request
event. But I cannot find anything in the trace
where I was expecting the info sent using _logger
. I checked the output window and also did not find any telemetry is sent against the _logger.LogInformation
.
What am I doing wrong in here and how can I make the Logger Info available to the ApplicationInsights
? Or am I not looking into the right place?
Application Insight defaults to Warning
as the log level. Since you are tracing with level Information
you need to configure application insights using the appsettings.json file:
{
"ApplicationInsights": {
"InstrumentationKey": "bd******-****-****-****-***********b"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Information"
}
}
"EventLog": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
}