下面用于LoggerConfiguration()初始化的代码在.net core 3控制台应用程序的Main()中起作用,但在工作程序服务中不起作用。使用控制台应用程序,在运行时创建了“ logs”文件夹和log.txt。运行服务时未创建该文件夹,因此我尝试了多个文件路径(“ c:\ log.txt”,“ .. \ log.txt”,“ .. \ .. \ log.txt”),但都没有被创造。日志显示在调试控制台中,但未创建log.txt文件。没有引发任何错误,VS 2019以管理员身份运行。
参考软件包:
<PackageReference Include="Serilog" Version="2.9.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
namespace WorkerService1
{
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File("logs\\log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
}
Worker.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WorkerService1
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
}
答案 0 :(得分:1)
我成为同一个名字奇怪的NuGet包的受害者。您需要添加Serilog.AspNetCore,即使它是一个控制台应用程序。有关更多信息,请参见本文:https://www.blinkingcaret.com/2018/02/14/net-core-console-logging/
答案 1 :(得分:0)
@ christopher-rosales的注释引用了.UseSerilog()。这需要一个额外的程序包Serilog.Extensions.Hosting。 Main()中Log.Logger的初始化无效,因此我将其添加到CreateHostBuilder()中。
Program.cs:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
namespace WorkerService1
{
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File("logs\\log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
})
.UseSerilog();
}
}