Skip to content

Commit c89b814

Browse files
committed
add dotnet versions
1 parent 9ad5883 commit c89b814

File tree

1 file changed

+126
-46
lines changed

1 file changed

+126
-46
lines changed

articles/azure-monitor/app/ilogger.md

Lines changed: 126 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -28,47 +28,91 @@ To add Application Insights logging to ASP.NET Core applications, use the `Micro
2828

2929
1. Add `ApplicationInsightsLoggerProvider`:
3030

31-
```csharp
32-
using Microsoft.AspNetCore.Hosting;
33-
using Microsoft.Extensions.DependencyInjection;
34-
using Microsoft.Extensions.Hosting;
35-
using Microsoft.Extensions.Logging;
36-
using Microsoft.Extensions.Logging.ApplicationInsights;
37-
38-
namespace WebApplication
31+
# [.NET 5.0](#tab/dotnet5)
32+
33+
```csharp
34+
using Microsoft.AspNetCore.Hosting;
35+
using Microsoft.Extensions.DependencyInjection;
36+
using Microsoft.Extensions.Hosting;
37+
using Microsoft.Extensions.Logging;
38+
using Microsoft.Extensions.Logging.ApplicationInsights;
39+
40+
namespace WebApplication
41+
{
42+
public class Program
3943
{
40-
public class Program
44+
public static void Main(string[] args)
4145
{
42-
public static void Main(string[] args)
43-
{
44-
var host = CreateHostBuilder(args).Build();
45-
46-
var logger = host.Services.GetRequiredService<ILogger<Program>>();
47-
logger.LogInformation("From Program, running the host now.");
48-
49-
host.Run();
50-
}
51-
52-
public static IHostBuilder CreateHostBuilder(string[] args) =>
53-
Host.CreateDefaultBuilder(args)
54-
.ConfigureWebHostDefaults(webBuilder =>
55-
{
56-
webBuilder.UseStartup<Startup>();
57-
})
58-
.ConfigureLogging((context, builder) =>
59-
{
60-
builder.AddApplicationInsights(
61-
configureTelemetryConfiguration: (config) => config.ConnectionString = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"],
62-
configureApplicationInsightsLoggerOptions: (options) => { }
63-
);
64-
65-
// Capture all log-level entries from Startup
66-
builder.AddFilter<ApplicationInsightsLoggerProvider>(
67-
typeof(Startup).FullName, LogLevel.Trace);
68-
});
46+
var host = CreateHostBuilder(args).Build();
47+
48+
var logger = host.Services.GetRequiredService<ILogger<Program>>();
49+
logger.LogInformation("From Program, running the host now.");
50+
51+
host.Run();
6952
}
53+
54+
public static IHostBuilder CreateHostBuilder(string[] args) =>
55+
Host.CreateDefaultBuilder(args)
56+
.ConfigureWebHostDefaults(webBuilder =>
57+
{
58+
webBuilder.UseStartup<Startup>();
59+
})
60+
.ConfigureLogging((context, builder) =>
61+
{
62+
builder.AddApplicationInsights(
63+
configureTelemetryConfiguration: (config) => config.ConnectionString = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"],
64+
configureApplicationInsightsLoggerOptions: (options) => { }
65+
);
66+
67+
// Capture all log-level entries from Startup
68+
builder.AddFilter<ApplicationInsightsLoggerProvider>(
69+
typeof(Startup).FullName, LogLevel.Trace);
70+
});
7071
}
71-
```
72+
}
73+
```
74+
75+
# [.NET 6.0+](#tab/dotnet6)
76+
77+
```csharp
78+
using Microsoft.Extensions.Logging.ApplicationInsights;
79+
80+
var builder = WebApplication.CreateBuilder(args);
81+
82+
// Add services to the container.
83+
84+
builder.Services.AddControllers();
85+
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
86+
builder.Services.AddEndpointsApiExplorer();
87+
builder.Services.AddSwaggerGen();
88+
89+
builder.Logging.AddApplicationInsights(
90+
configureTelemetryConfiguration: (config) =>
91+
config.ConnectionString = builder.Configuration.GetConnectionString("APPLICATIONINSIGHTS_CONNECTION_STRING"),
92+
configureApplicationInsightsLoggerOptions: (options) => { }
93+
);
94+
95+
builder.Logging.AddFilter<ApplicationInsightsLoggerProvider>("your-category", LogLevel.Trace);
96+
97+
var app = builder.Build();
98+
99+
// Configure the HTTP request pipeline.
100+
if (app.Environment.IsDevelopment())
101+
{
102+
app.UseSwagger();
103+
app.UseSwaggerUI();
104+
}
105+
106+
app.UseHttpsRedirection();
107+
108+
app.UseAuthorization();
109+
110+
app.MapControllers();
111+
112+
app.Run();
113+
```
114+
115+
---
72116

73117
With the NuGet package installed, and the provider being registered with dependency injection, the app is ready to log. With constructor injection, either <xref:Microsoft.Extensions.Logging.ILogger> or the generic-type alternative <xref:Microsoft.Extensions.Logging.ILogger%601> is required. When these implementations are resolved, `ApplicationInsightsLoggerProvider` will provide them. Logged messages or exceptions will be sent to Application Insights.
74118

@@ -99,18 +143,14 @@ For more information, see [Logging in ASP.NET Core](/aspnet/core/fundamentals/lo
99143

100144
## Console application
101145

102-
To add Application Insights logging to console applications, first install the [`Microsoft.Extensions.Logging.ApplicationInsights`][nuget-ai] NuGet provider package.
146+
To add Application Insights logging to console applications, first install the following packages:
103147

104-
The following example uses the Microsoft.Extensions.Logging.ApplicationInsights package and demonstrates the default behavior for a console application. The Microsoft.Extensions.Logging.ApplicationInsights package should be used in a console application or whenever you want a bare minimum implementation of Application Insights without the full feature set such as metrics, distributed tracing, sampling, and telemetry initializers.
148+
* [`Microsoft.Extensions.Logging.ApplicationInsights`][nuget-ai] NuGet provider package.
149+
* [`Microsoft.Extensions.DependencyInjection`][nuget-ai] NuGet provider package.
105150

106-
Here are the installed packages:
151+
The following example uses the Microsoft.Extensions.Logging.ApplicationInsights package and demonstrates the default behavior for a console application. The Microsoft.Extensions.Logging.ApplicationInsights package should be used in a console application or whenever you want a bare minimum implementation of Application Insights without the full feature set such as metrics, distributed tracing, sampling, and telemetry initializers.
107152

108-
```xml
109-
<ItemGroup>
110-
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.0" />
111-
<PackageReference Include="Microsoft.Extensions.Logging.ApplicationInsights" Version="2.17.0"/>
112-
</ItemGroup>
113-
```
153+
# [.NET 5.0](#tab/dotnet5)
114154

115155
```csharp
116156
using Microsoft.ApplicationInsights.Channel;
@@ -161,6 +201,46 @@ namespace ConsoleApp
161201

162202
```
163203

204+
# [.NET 6.0+](#tab/dotnet6)
205+
206+
```csharp
207+
using Microsoft.ApplicationInsights.Channel;
208+
using Microsoft.ApplicationInsights.Extensibility;
209+
using Microsoft.Extensions.DependencyInjection;
210+
using Microsoft.Extensions.Logging;
211+
212+
using var channel = new InMemoryChannel();
213+
214+
try
215+
{
216+
IServiceCollection services = new ServiceCollection();
217+
services.Configure<TelemetryConfiguration>(config => config.TelemetryChannel = channel);
218+
services.AddLogging(builder =>
219+
{
220+
// Only Application Insights is registered as a logger provider
221+
builder.AddApplicationInsights(
222+
configureTelemetryConfiguration: (config) => config.ConnectionString = "<YourConnectionString>",
223+
configureApplicationInsightsLoggerOptions: (options) => { }
224+
);
225+
});
226+
227+
IServiceProvider serviceProvider = services.BuildServiceProvider();
228+
ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();
229+
230+
logger.LogInformation("Logger is working...");
231+
}
232+
finally
233+
{
234+
// Explicitly call Flush() followed by Delay, as required in console apps.
235+
// This ensures that even if the application terminates, telemetry is sent to the back end.
236+
channel.Flush();
237+
238+
await Task.Delay(TimeSpan.FromMilliseconds(1000));
239+
}
240+
```
241+
242+
---
243+
164244
## Frequently asked questions
165245

166246
### Why do some ILogger logs not have the same properties as others?

0 commit comments

Comments
 (0)