我正在将源代码从旧的dotnetframework控制台迁移到dotnetcore 3.1 console / workser-service。
在查看了Google研究的一些文章和示例之后,我仍然对为什么日志无法正常工作有些困惑。因此,我将在下面附上两个示例。第一个有效,但第二个无效。我需要提升权限或其他我不知道的东西吗?
[示例1-有效]
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Hosting.WindowsServices;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;
using System.Threading.Tasks;
namespace ABCoA.Payments.EtlManager.WorkerSvc
{
public class Program
{
public async static Task Main(string[] args)
{
var loggerFactory = LoggerFactory.Create(builder => {
builder
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning)
.AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
.AddConsole()
.AddEventLog();
});
ILogger logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation("Example log message");
}
}
}
[示例#2-不起作用]
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;
using System.Threading.Tasks;
namespace ABCoA.Payments.EtlManager.WorkerSvc
{
public class Program
{
public async static Task Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureLogging((context, logging) => logging.AddEventLog(
new EventLogSettings()
{
SourceName = "MySource",
LogName = "MyLogName"
}
))
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<WorkerService>();
});
}
}
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ABCoA.Payments.EtlManager.WorkerSvc
{
public class WorkerService : BackgroundService
{
private readonly ILogger<WorkerService> _logger;
public WorkerService(ILogger<WorkerService> logger)
{
_logger = logger;
}
public override async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation($"Worker Service started at: {DateTime.Now}");
await base.StartAsync(cancellationToken);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation($"Worker Service stopped at: {DateTime.Now}");
await base.StopAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation($"Worker Service running at: {DateTime.Now}");
await Task.Delay(1000, stoppingToken);
}
}
}
}
"Logging": {
"IncludeScopes": "true",
"LogLevel": {
"Default": "Information",
//"System": "Information",
"Microsoft": "Warning",
//"ABCoA": "Verbose",
"Microsoft.Hosting.Lifetime": "Information"
},
"EventLog": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}