gpt4 book ai didi

c# - Serilog 不会将日志输出到 txt 文件中

转载 作者:行者123 更新时间:2023-12-05 00:53:40 25 4
gpt4 key购买 nike

我正在使用 dotnet worker 服务 (.net 5)我集成了 serilog 以及丰富器和接收器。但由于某种原因,我在文件日志中看不到任何输出。

这是我的 appsettings.json

{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=eeee;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"WorkerOptions": {
"Batch": 5
},
"Serilog": {
"Using": [],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "E:\\Logs\\log_.txt",
"outputTemplate": "{Timestamp:o} {Message}{NewLine:1}{Exception:1}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
},
{
"Name": "File",
"Args": {
"path": "E:\\Logs\\log_.json",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
"outputTemplate": "{Timestamp:o} {Message}{NewLine:1}{Exception:1}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
]
}
}

记录器的注册:

public class Program
{
public static void Main(string[] args)
{

var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();

CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)

.ConfigureServices((hostContext, services) =>
{

var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
services.AddScoped<ApplicationDbContext>(s => new ApplicationDbContext(optionsBuilder.Options));
services.AddHostedService<Worker>();
});
}

这是一个实现:

public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IConfiguration _config;
public Worker(ILogger<Worker> logger, IServiceScopeFactory serviceScopeFactory, IConfiguration config)
{
_config = config;
_logger = logger;
_serviceScopeFactory = serviceScopeFactory;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Worker picked up {0} requests for dispatch at at: {time}", generatedRequests.Count(), DateTimeOffset.Now);
}

当我通过 Kestrel 运行工作程序时,我可以在控制台日志中看到,但在 .txt 文件或 .json 文件中看不到

更新 #1我在下面尝试了这个答案,但是当我部署我的工作人员时仍然遇到问题,我没有看到任何日志。当我通过 service.exe 文件运行它或只是进行调试(Kestrel)时,会生成日志文件。

这里是更新的application.json:

"Serilog": {
"Using": [],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": ".\\Logs\\log_.txt",
"outputTemplate": "{Timestamp:o} {Message}{NewLine:1}{Exception:1}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
},
{
"Name": "File",
"Args": {
"path": ".\\Logs\\log_.json",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
"outputTemplate": "{Timestamp:o} {Message}{NewLine:1}{Exception:1}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
]
}

这是 Program.cs

public class Program
{
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();

CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{

var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer(hostContext.Configuration.GetConnectionString("DefaultConnection"));
services.AddScoped<ApplicationDbContext>(s => new ApplicationDbContext(optionsBuilder.Options));
services.AddHostedService<Worker>();
})
.UseSerilog(); // no args
}

更新#2我像这样更新了 Program 类:

public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{

var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer(hostContext.Configuration.GetConnectionString("DefaultConnection"));
services.AddScoped<ApplicationDbContext>(s => new ApplicationDbContext(optionsBuilder.Options));
services.AddHostedService<Worker>();
})
.UseSerilog((hostContext, services, logger) => {
logger.ReadFrom.Configuration(hostContext.Configuration);
});
}
}

我还在 appsettings.json 中放了一些简单的东西:

  "Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": { "path": "Logs/log.txt" }
},
//{
// "Name": "File",
// "Args": {
// "path": ".\\Logs\\log_.txt",
// "outputTemplate": "{Timestamp:o} {Message}{NewLine:1}{Exception:1}",
// "rollingInterval": "Day",
// "retainedFileCountLimit": 7
// }
//},
{
"Name": "File",
"Args": {
"path": ".\\Logs\\log_.json",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
"outputTemplate": "{Timestamp:o} {Message}{NewLine:1}{Exception:1}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
]
}

当我启动 .exe 文件(控制台)时,再次调用正在工作的 _logger

using Microsoft.Extensions.Logging;
...
private readonly ILogger<Worker> _logger;
...
_logger.LogInformation("Worker picked up {0} requests for dispatch at: {time}", generatedRequests.Count(), DateTimeOffset.Now);

更新#3我只是为记录 c:\\Logs\log.txt 设置了绝对路径,它部分工作 - 它创建一个 txt 文件,但文件为空。这是新的 appsettings.json:

{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=svcProcessor_dev;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"WorkerOptions": {
"Batch": 10,
"Delay": 5000,
"MaxAttempts": 3
},
"Serilog": {
"Using": ["Serilog.Sinks.Console", "Serilog.Sinks.File"],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": { "path": "C:\\Logs\\log.txt" }
}
//{
// "Name": "File",
// "Args": {
// "path": "C:\\Logs\\log_.txt",
// "outputTemplate": "{Timestamp:o} {Message}{NewLine:1}{Exception:1}",
// "rollingInterval": "Day",
// "retainedFileCountLimit": 7
// }
//}
//{
// "Name": "File",
// "Args": {
// "path": "C:\\Logs\\log_.json",
// "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
// "outputTemplate": "{Timestamp:o} {Message}{NewLine:1}{Exception:1}",
// "rollingInterval": "Day",
// "retainedFileCountLimit": 7
// }
//}
]
}
}

更新#4

这是我的 worker 的最小示例 worker example

最佳答案

您没有添加基础架构来转换 Serilog 的 Logger变成 Microsoft.Extensions.Logging.ILogger .就目前而言,您只是在创建 Serilog Logger,但并未实际使用它。您在控制台中看到的实际上是来自内置 Microsoft 记录器的日志,而不是来自 Serilog 的

幸运的是,Serilog 有一个从他们的记录器到 Microsoft 记录器接口(interface)的适配器和各种帮助程序包,具体取决于您的使用场景。您使用的是通用主机,所以首先添加 Serilog.Extensions.Hosting package到你的项目。然后调用UseSerilog扩展方法。传递给此方法的委托(delegate)接收 HostBuilderContext 的实例您可以从中检索当前的IConfiguration以及 IServiceProviderLoggingConfiguration你用来配置记录器:

public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
/* elided */
})
.UseSerilog((hostContext, services, logger) => {
logger.ReadFrom.Configuration(hostContext.Configuration);
});

请注意,不再需要设置 Log.Logger属性(property)并建立 LoggerConfiguration直接来自Main . UseSerilog方法将自动设置静态记录器——尽管您不需要它,但您正在通过 ILogger<> 进行记录无论如何。

或者,您可以配置您当前执行的记录器方式(直接在 Main 中)。如果你走这条路,你会调用UseSerilog没有任何参数。这将反过来使用静态记录器的当前配置。

public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

Log.Logger = new LoggingConfiguration()
.ReadFromConfiguration(config)
.CreateLogger();

CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
/* elided */
})
.UseSerilog(); // no args

我个人不喜欢这个选项,尤其是在使用 ReadFrom.Configuration 时因为它需要您构建一个额外的配置对象。我更喜欢使用传入回调的那个,因为它将匹配主机使用的所有其他配置。

ASP.NET 核心

您使用 aspnet-core 标记了您的问题并在您的问题中提及“Kestrel”。但是,您演示的代码显示了一个非常基本的通用主机,不是一个 Web 应用程序。如果这个 真的 是一个网络应用程序,那么你可以添加 Serilog.AspNetCore package反而。该包隐式引用 Serilog.Extensions.Hosting并包括一些其他可在 Web 应用程序中使用的点点滴滴。

关于c# - Serilog 不会将日志输出到 txt 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67300156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com