.NET Core 3.0 Worker 是一个轻量级的、无界面的应用程序模型,适用于长时间运行的服务。它非常适合用于后台任务、微服务和服务器应用程序。Worker 通过宿主(Host)来运行,宿主负责管理应用程序的生命周期和依赖注入。
IHostedService
接口实现自定义的服务。BackgroundService
类,简化后台任务的实现。在 .NET Core 3.0 Worker 中,无法使用 Application Insights 或 EventLog 进行日志记录的问题可能是由于以下原因:
确保已安装 Microsoft.ApplicationInsights.AspNetCore
和 Microsoft.ApplicationInsights.WorkerService
NuGet 包。
dotnet add package Microsoft.ApplicationInsights.AspNetCore
dotnet add package Microsoft.ApplicationInsights.WorkerService
在 appsettings.json
中添加 Application Insights 配置:
{
"ApplicationInsights": {
"InstrumentationKey": "your-instrumentation-key"
}
}
在 Program.cs
中配置 Application Insights:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
var appInsightsConfig = config.GetSection("ApplicationInsights");
config.AddInMemoryCollection(new Dictionary<string, string>
{
{ "ApplicationInsights:InstrumentationKey", appInsightsConfig["InstrumentationKey"] }
});
})
.ConfigureServices((hostContext, services) =>
{
services.AddApplicationInsightsTelemetryWorkerService();
services.AddHostedService<Worker>();
});
}
确保已安装 Microsoft.Extensions.Logging.EventLog
NuGet 包。
dotnet add package Microsoft.Extensions.Logging.EventLog
在 appsettings.json
中添加 EventLog 配置:
{
"Logging": {
"EventLog": {
"LogName": "Application",
"MachineName": "."
}
}
}
在 Program.cs
中配置 EventLog:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((context, logging) =>
{
logging.AddEventLog(eventLogSettings =>
{
eventLogSettings.LogName = context.Configuration["Logging:EventLog:LogName"];
eventLogSettings.MachineName = context.Configuration["Logging:EventLog:MachineName"];
});
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
确保应用程序有足够的权限写入 EventLog。可以在 app.manifest
文件中添加以下内容:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
通过以上配置和解决方法,应该能够在 .NET Core 3.0 Worker 中成功使用 Application Insights 和 EventLog 进行日志记录。