I wanted to add logs on the Azure Application Insights in my application, ASP.Net Web application MVC, .Net Framework is 4.6.2.
I do have added references to below nuget packages
- Microsoft.ApplicationInsights
- Microsoft.Extensions.Logging
I do have added below code in Global.asax.cs in the applicatin_start
TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
Inside HomeController.cs, I have added below code, but it is giving me below error at the line _logger.LogTrace()
Error
System.ArgumentNullException: ‘Value cannot be null.
Parameter name: logger’
Code
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController()
{
IServiceCollection services = new ServiceCollection();
IServiceProvider serviceProvider = services.BuildServiceProvider();
_logger = serviceProvider.GetService<ILogger<HomeController>>();
}
public ActionResult Index()
{
ViewBag.Title = "Home Page";
_logger.LogTrace("Some trace message from Version 462");
return View();
}
}
Please let me know where I am going wrong.
Thanks,
Tushar
2
Answers
Below are the steps to resolve this issue.
Navigate to your Project >> Add Application Insights Telemetry >> Application Insights Sdk (local) >> Next >> Finish >> Close.
In the Global.asax.cs add below line
TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
Wherever wanted to add application insights add below code, you can create common logger file also.
Initially, you need to add Application Insights. Below are the steps you can follow to add Application Insights to your Application.
Navigate to your Project >> Add Application Insights Telemetry >> Application Insights Sdk (local) >> Next >> Finish >> Close.
You can register the initializer through
applicationinsights.config
file, while Adding Application Insights automatically we need to add the instrumentation key toApplicationInsights.config
before closing the</ApplicationInsights>
tag file.OR
And while logging in from your Home Controller try
After updating the Nuget packages, you can run your application where you can observe that telemetry will be submitted to Application Insights when you navigate the site’s pages.
If Adding Application Insights Automatically isn’t working, then you can try manually from HERE.
REFERENCE :