@@ -22,53 +22,97 @@ In this article, you'll learn how to capture logs with Application Insights in .
22
22
23
23
## ASP.NET Core applications
24
24
25
- To add Application Insights logging to ASP.NET Core applications, use the ` Microsoft.Extensions.Logging.ApplicationInsights ` NuGet provider package.
25
+ To add Application Insights logging to ASP.NET Core applications:
26
26
27
- 1 . Install the [ ` Microsoft.Extensions.Logging.ApplicationInsights ` ] [ nuget-ai ] NuGet package .
27
+ 1 . Install the [ ` Microsoft.Extensions.Logging.ApplicationInsights ` ] [ nuget-ai ] .
28
28
29
29
1 . Add ` ApplicationInsightsLoggerProvider ` :
30
30
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 6.0+] ( #tab/dotnet6 )
32
+
33
+ ``` csharp
34
+ using Microsoft .Extensions .Logging .ApplicationInsights ;
35
+
36
+ var builder = WebApplication .CreateBuilder (args );
37
+
38
+ // Add services to the container.
39
+
40
+ builder .Services .AddControllers ();
41
+ // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
42
+ builder .Services .AddEndpointsApiExplorer ();
43
+ builder .Services .AddSwaggerGen ();
44
+
45
+ builder .Logging .AddApplicationInsights (
46
+ configureTelemetryConfiguration : (config ) =>
47
+ config .ConnectionString = builder .Configuration .GetConnectionString (" APPLICATIONINSIGHTS_CONNECTION_STRING" ),
48
+ configureApplicationInsightsLoggerOptions : (options ) => { }
49
+ );
50
+
51
+ builder .Logging .AddFilter <ApplicationInsightsLoggerProvider >(" your-category" , LogLevel .Trace );
52
+
53
+ var app = builder .Build ();
54
+
55
+ // Configure the HTTP request pipeline.
56
+ if (app .Environment .IsDevelopment ())
57
+ {
58
+ app .UseSwagger ();
59
+ app .UseSwaggerUI ();
60
+ }
61
+
62
+ app .UseHttpsRedirection ();
63
+
64
+ app .UseAuthorization ();
65
+
66
+ app .MapControllers ();
67
+
68
+ app .Run ();
69
+ ```
70
+
71
+ # [ .NET 5.0] ( #tab/dotnet5 )
72
+
73
+ ``` csharp
74
+ using Microsoft .AspNetCore .Hosting ;
75
+ using Microsoft .Extensions .DependencyInjection ;
76
+ using Microsoft .Extensions .Hosting ;
77
+ using Microsoft .Extensions .Logging ;
78
+ using Microsoft .Extensions .Logging .ApplicationInsights ;
79
+
80
+ namespace WebApplication
81
+ {
82
+ public class Program
39
83
{
40
- public class Program
84
+ public static void Main ( string [] args )
41
85
{
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
- });
86
+ var host = CreateHostBuilder (args ).Build ();
87
+
88
+ var logger = host .Services .GetRequiredService <ILogger <Program >>();
89
+ logger .LogInformation (" From Program, running the host now." );
90
+
91
+ host .Run ();
69
92
}
93
+
94
+ public static IHostBuilder CreateHostBuilder (string [] args ) =>
95
+ Host .CreateDefaultBuilder (args )
96
+ .ConfigureWebHostDefaults (webBuilder =>
97
+ {
98
+ webBuilder .UseStartup <Startup >();
99
+ })
100
+ .ConfigureLogging ((context , builder ) =>
101
+ {
102
+ builder .AddApplicationInsights (
103
+ configureTelemetryConfiguration : (config ) => config .ConnectionString = context .Configuration [" APPLICATIONINSIGHTS_CONNECTION_STRING" ],
104
+ configureApplicationInsightsLoggerOptions : (options ) => { }
105
+ );
106
+
107
+ // Capture all log-level entries from Startup
108
+ builder .AddFilter <ApplicationInsightsLoggerProvider >(
109
+ typeof (Startup ).FullName , LogLevel .Trace );
110
+ });
70
111
}
71
- ```
112
+ }
113
+ ```
114
+
115
+ ---
72
116
73
117
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.
74
118
@@ -99,19 +143,53 @@ For more information, see [Logging in ASP.NET Core](/aspnet/core/fundamentals/lo
99
143
100
144
## Console application
101
145
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 NuGet packages:
147
+
148
+ * [ ` Microsoft.Extensions.Logging.ApplicationInsights ` ] [ nuget-ai ]
149
+ * [ ` Microsoft.Extensions.DependencyInjection ` ] [ nuget-ai ]
103
150
104
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.
105
152
106
- Here are the installed packages:
153
+ # [ .NET 6.0+] ( #tab/dotnet6 )
154
+
155
+ ``` csharp
156
+ using Microsoft .ApplicationInsights .Channel ;
157
+ using Microsoft .ApplicationInsights .Extensibility ;
158
+ using Microsoft .Extensions .DependencyInjection ;
159
+ using Microsoft .Extensions .Logging ;
160
+
161
+ using var channel = new InMemoryChannel ();
162
+
163
+ try
164
+ {
165
+ IServiceCollection services = new ServiceCollection ();
166
+ services .Configure <TelemetryConfiguration >(config => config .TelemetryChannel = channel );
167
+ services .AddLogging (builder =>
168
+ {
169
+ // Only Application Insights is registered as a logger provider
170
+ builder .AddApplicationInsights (
171
+ configureTelemetryConfiguration : (config ) => config .ConnectionString = " <YourConnectionString>" ,
172
+ configureApplicationInsightsLoggerOptions : (options ) => { }
173
+ );
174
+ });
175
+
176
+ IServiceProvider serviceProvider = services .BuildServiceProvider ();
177
+ ILogger < Program > logger = serviceProvider .GetRequiredService <ILogger <Program >>();
107
178
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 >
179
+ logger .LogInformation (" Logger is working..." );
180
+ }
181
+ finally
182
+ {
183
+ // Explicitly call Flush() followed by Delay, as required in console apps.
184
+ // This ensures that even if the application terminates, telemetry is sent to the back end.
185
+ channel .Flush ();
186
+
187
+ await Task .Delay (TimeSpan .FromMilliseconds (1000 ));
188
+ }
113
189
```
114
190
191
+ # [ .NET 5.0] ( #tab/dotnet5 )
192
+
115
193
``` csharp
116
194
using Microsoft .ApplicationInsights .Channel ;
117
195
using Microsoft .ApplicationInsights .Extensibility ;
@@ -161,6 +239,8 @@ namespace ConsoleApp
161
239
162
240
```
163
241
242
+ ---
243
+
164
244
## Frequently asked questions
165
245
166
246
### Why do some ILogger logs not have the same properties as others?
0 commit comments