【发布时间】:2022-01-10 22:25:22
【问题描述】:
我一直在构建一个工具来解决一些与数据相关的问题。底线是在 .Net 5.0 中,未来将移植到 .net 6.0。
我过去使用 Serilog 没有问题。但作为我的“工具”的一部分,我需要使用 TCP 服务器。我选择使用 WastonTCP,因为它很简单。
问题在于它使用 MS Logger 工厂并默认输出到控制台。不是生产所需的结果。
当我现在运行应用程序时,我会在日志中看到启动和停止消息,但这些都没有显示在下面
这些消息我想要在 serilog 中。 这是program.cs代码:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Enrichers;
using Serilog.Events;
using System;
namespace PostDataService
{
public class Program
{
public static void Main(string[] args)
{
const string _logTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff}\t{EnvironmentUserName}\t[{Level:u4}]\t<{ThreadId}>\t{Message:lj}{NewLine}{Exception}";
var loggerConfig = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Verbose)
.Enrich.WithThreadId()
.Enrich.WithEnvironmentUserName()
.WriteTo.File("./App_Data/logs/USPS.Log",
fileSizeLimitBytes: 524288000,
outputTemplate: _logTemplate);
Log.Logger = loggerConfig.CreateLogger();
try
{
Log.Write(LogEventLevel.Information, "Start USPS Data Server");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
Log.Information("USPS Server stopped");
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
}
我对 MS 记录器工具非常陌生,因此不确定这是否是问题和/或我将 TCP 服务器作为后台工作程序运行的事实存在问题。
这是 worker.cs 中的 ExecuteAsync 方法,它在屏幕截图中生成第一条消息。
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
//_logger.LogInformation("Worker running at: {time} {threadid}", DateTimeOffset.Now, Thread.CurrentThread.ManagedThreadId);
while (!stoppingToken.IsCancellationRequested)
{
if (_msgcnt == 0 || (_msgcnt % 500 == 0) )
{
_logger.LogInformation("Worker running at: {time} {threadid}", DateTimeOffset.Now, Thread.CurrentThread.ManagedThreadId);
}
//_logger.LogInformation("Worker running at: {time} {threadid}", DateTimeOffset.Now, Thread.CurrentThread.ManagedThreadId);
_msgcnt++;
await Task.Delay(500, stoppingToken);
}
//_Server.Stop();
}
这里是appsettings.Developement.json(和appsettings.json一样):
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"FormatterOptions": {
"SingleLine": true
}
}
}
【问题讨论】:
标签: c# logging .net-5 .net-6.0