.NET 4.7.2 WebForms中如何为ILogger添加App Insights及事件查看器提供程序?
在.NET 4.7.2 WebForms中为ILogger添加App Insights和事件查看器日志提供程序
你可以通过安装对应日志提供程序的NuGet包,再在AddLogging的配置委托中注册它们,来为你的ILogger实例添加事件查看器和App Insights支持,具体操作如下:
1. 安装所需NuGet包
在你的.NET 4.7.2 WebForms项目中安装以下两个包:
Microsoft.Extensions.Logging.EventLog:用于事件查看器日志提供Microsoft.Extensions.Logging.ApplicationInsights:用于App Insights日志提供
可通过NuGet包管理器控制台执行命令:
Install-Package Microsoft.Extensions.Logging.EventLog Install-Package Microsoft.Extensions.Logging.ApplicationInsights
2. 配置日志提供程序
修改创建ILogger的代码,在AddLogging中添加两个提供程序的配置:
var serviceCollection = new ServiceCollection(); serviceCollection.AddLogging(loggingBuilder => { // 配置事件查看器提供程序 loggingBuilder.AddEventLog(options => { // 可选:自定义事件日志源名称,默认是"Application" options.SourceName = "YourWebFormsApp"; // 可选:设置日志级别过滤,例如只记录Warning及以上级别 options.Filter = (category, level) => level >= LogLevel.Warning; }); // 配置App Insights提供程序 loggingBuilder.AddApplicationInsights(options => { // 替换为你的App Insights仪表密钥 options.InstrumentationKey = "Your-App-Insights-Instrumentation-Key"; }); }); var serviceProvider = serviceCollection.BuildServiceProvider(); // 建议使用带泛型的ILogger<T>,便于日志分类排查 ILogger logger = serviceProvider.GetService<ILogger<YourTargetClass>>();
关键注意点:
- 优先使用
ILogger<TCategoryName>(比如ILogger<YourPage>或ILogger<YourBusinessService>)而非无泛型的ILogger,这样日志会携带清晰的分类标识,方便定位问题。 - App Insights的仪表密钥可从Azure门户获取,也可以从Web.config配置项中读取,示例:
options.InstrumentationKey = System.Configuration.ConfigurationManager.AppSettings["AppInsightsKey"]; - 事件查看器的日志会显示在Windows事件查看器的「Windows日志」→「应用程序」节点下,源名称为你配置的值。
完成上述配置后,你的ILogger实例会同时将日志发送到事件查看器和App Insights,且与.NET 6 Core端的ILogger使用逻辑一致,确保跨平台类库的日志接口兼容。
内容的提问来源于stack exchange,提问作者Jatin
相关产品推荐
相关产品推荐

