Connecting .NET with Azure Application Insights (All Logging Types)
What is Azure Application Insights?
Azure Application Insights is a powerful tool that helps you understand how your application is running in real-time. It provides visibility into application performance, errors, usage, and more—so you can identify and fix issues faster.
Step 1: Install Application Insights SDK
Run this command in your terminal to add the Application Insights package:
dotnet add package Microsoft.ApplicationInsights.AspNetCore
Step 2: Configure in appsettings.json
Add your Application Insights connection string:
{
"ApplicationInsights": {
"ConnectionString": "InstrumentationKey=your-instrumentation-key"
}
}
Step 3: Modify Program.cs
(for .NET 6+)
var builder = WebApplication.CreateBuilder(args);
// Add Application Insights
builder.Services.AddApplicationInsightsTelemetry(
builder.Configuration["ApplicationInsights:ConnectionString"]);
var app = builder.Build();
app.MapControllers(); // Ensure controllers are mapped
app.Run();
Step 4: Create Logging Controller
Below is a sample controller demonstrating different types of telemetry logging using TelemetryClient
.
using Microsoft.AspNetCore.Mvc;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using System;
using System.Collections.Generic;
[ApiController]
[Route("api/[controller]")]
public class TelemetryDemoController : ControllerBase
{
private readonly TelemetryClient _telemetryClient;
public TelemetryDemoController(TelemetryClient telemetryClient)
{
_telemetryClient = telemetryClient;
}
// VERBOSE TRACE
[HttpGet("trace-verbose")]
public IActionResult LogVerbose()
{
var message = "This is a VERBOSE log";
var timestamp = DateTime.UtcNow;
_telemetryClient.TrackTrace(message, SeverityLevel.Verbose);
var logObject = new
{
message = message,
severityLevel = "Verbose",
timestamp = timestamp.ToString("o"),
type = "Trace"
};
return Ok(logObject);
}
// INFORMATION TRACE
[HttpGet("trace-info")]
public IActionResult LogInfo()
{
var message = "This is an INFORMATION log";
var timestamp = DateTime.UtcNow;
_telemetryClient.TrackTrace(message, SeverityLevel.Information);
var logObject = new
{
message = message,
severityLevel = "Information",
timestamp = timestamp.ToString("o"),
type = "Trace"
};
return Ok(logObject);
}
// WARNING TRACE
[HttpGet("trace-warning")]
public IActionResult LogWarning()
{
var message = "This is a WARNING log";
var timestamp = DateTime.UtcNow;
_telemetryClient.TrackTrace(message, SeverityLevel.Warning);
var logObject = new
{
message = message,
severityLevel = "Warning",
timestamp = timestamp.ToString("o"),
type = "Trace"
};
return Ok(logObject);
}
// EXCEPTION
[HttpGet("log-exception")]
public IActionResult LogException()
{
string message = null;
string type = null;
string stackTrace = null;
var timestamp = DateTime.UtcNow;
try
{
int fail = 0;
int result = 10 / fail;
}
catch (Exception ex)
{
message = ex.Message;
type = ex.GetType().Name;
stackTrace = ex.StackTrace;
_telemetryClient.TrackException(ex);
}
var logObject = new
{
type = "Exception",
exception = new
{
message = message,
type = type,
stackTrace = stackTrace
},
severityLevel = "Error",
timestamp = timestamp.ToString("o")
};
return Ok(logObject);
}
// CUSTOM EVENT
[HttpGet("log-event")]
public IActionResult LogEvent()
{
var eventName = "UserSignedUp";
var timestamp = DateTime.UtcNow;
var properties = new Dictionary
{
{ "Plan", "Premium" },
{ "Region", "East US" }
};
_telemetryClient.TrackEvent(eventName, properties);
var logObject = new
{
type = "Event",
name = eventName,
properties = properties,
timestamp = timestamp.ToString("o")
};
return Ok(logObject);
}
// DEPENDENCY
[HttpGet("log-dependency")]
public IActionResult LogDependency()
{
var dependencyType = "SQL";
var dependencyName = "GetUsers";
var dependencyData = "SELECT * FROM Users";
var timestamp = DateTimeOffset.UtcNow;
var duration = TimeSpan.FromMilliseconds(200);
var success = true;
_telemetryClient.TrackDependency(
dependencyType,
dependencyName,
dependencyData,
timestamp,
duration,
success
);
var logObject = new
{
type = "Dependency",
target = dependencyType,
name = dependencyName,
data = dependencyData,
duration = duration.ToString(),
success = success,
timestamp = timestamp.ToString("o")
};
return Ok(logObject);
}
// REQUEST
[HttpGet("log-request")]
public IActionResult LogRequest()
{
var requestName = "HomePageRequest";
var timestamp = DateTimeOffset.UtcNow;
var duration = TimeSpan.FromMilliseconds(150);
var responseCode = "200";
var success = true;
_telemetryClient.TrackRequest(
requestName,
timestamp,
duration,
responseCode,
success
);
var logObject = new
{
type = "Request",
name = requestName,
duration = duration.ToString(),
responseCode = responseCode,
success = success,
timestamp = timestamp.ToString("o")
};
return Ok(logObject);
}
}
Step 5: Test Logging via Browser or Postman
Once your app is running, open a browser or use Postman and navigate to:
- GET
/api/TelemetryDemo/trace-verbose
- GET
/api/TelemetryDemo/trace-info
- GET
/api/TelemetryDemo/trace-warning
- GET
/api/TelemetryDemo/log-exception
- GET
/api/TelemetryDemo/log-event
- GET
/api/TelemetryDemo/log-request
- GET
/api/TelemetryDemo/log-dependency
Step 6: View Telemetry in Azure
Go to the Azure Portal and open your Application Insights resource to view:
- ✔️ Logs: Search and filter all telemetry
- ✔️ Live Metrics: Watch events in real-time
- ✔️ Failures: View and diagnose exceptions
- ✔️ Performance: Monitor response times
- ✔️ Custom Events: Track user behavior