|
| 1 | +// Necessary using statements. |
| 2 | +using ApplicationInsights.RedactSensitiveInformation; |
| 3 | +using Microsoft.ApplicationInsights; |
| 4 | +using Microsoft.ApplicationInsights.Extensibility; |
| 5 | +using Microsoft.ApplicationInsights.WorkerService; |
| 6 | +using Microsoft.Extensions.DependencyInjection; |
| 7 | +using Microsoft.Extensions.Logging; |
| 8 | +using Microsoft.Extensions.Logging.ApplicationInsights; |
| 9 | + |
| 10 | +// DEMO ONLY: Don't put credentials in code - use Azure Key Vault, or applicable protected configuration services. |
| 11 | +// I am using the connection string in code for clarity and avoiding unnecessary logic that distracts from the focus of the demo. |
| 12 | +const string connectionString = "InstrumentationKey=<GUID>;IngestionEndpoint=https://<endpoint>.in.applicationinsights.azure.com/;LiveEndpoint=https://<endpoint>.livediagnostics.monitor.azure.com/"; |
| 13 | + |
| 14 | +#region Wire-up |
| 15 | + |
| 16 | +// |
| 17 | +// Wire-up. |
| 18 | +// |
| 19 | +IServiceCollection services = new ServiceCollection(); |
| 20 | + |
| 21 | +// Add ApplicationInsightsLoggerProvider logger. |
| 22 | +services.AddLogging(loggingBuilder => loggingBuilder.AddFilter<ApplicationInsightsLoggerProvider>("Category", LogLevel.Information)); |
| 23 | + |
| 24 | +// Add Application Insights logic (ApplicationInsightsTelemetryWorkerService) |
| 25 | +services.AddApplicationInsightsTelemetryWorkerService((ApplicationInsightsServiceOptions options) => options.ConnectionString = connectionString); |
| 26 | + |
| 27 | + |
| 28 | +// NOTE: Injecting the SensitivityRedaction initializer. |
| 29 | +services.AddSingleton<ITelemetryInitializer, SensitivityRedactionTelemetryInitializer>(); |
| 30 | + |
| 31 | + |
| 32 | +IServiceProvider serviceProvider = services.BuildServiceProvider(); |
| 33 | + |
| 34 | +#endregion |
| 35 | + |
| 36 | + |
| 37 | +// |
| 38 | +// NOTE: Program logic to demonstrate |
| 39 | +// |
| 40 | + |
| 41 | +// Get the app insights ILogger from the service provider. |
| 42 | +ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>(); |
| 43 | + |
| 44 | + |
| 45 | +// Sending a few log messages. Some include PII, some does not. |
| 46 | +logger.LogWarning("This is a log message without PII."); |
| 47 | +logger.LogWarning("This is a log message with an e-mail: [email protected]"); |
| 48 | +logger.LogWarning("This is another message with [email protected], and [email protected]"); |
| 49 | +logger.LogWarning("Users access restrictions changed for: [email protected];[email protected], new access level is 'Reader' on resource '123'"); |
| 50 | + |
| 51 | + |
| 52 | +// For demo purposes in our console app. |
| 53 | +// Used to directly flush the buffer before we quit the app. |
| 54 | +var telemetryClient = serviceProvider.GetRequiredService<TelemetryClient>(); |
| 55 | +telemetryClient.Flush(); |
| 56 | +Task.Delay(5000).Wait(); |
| 57 | + |
0 commit comments