Serilog 不会创建日志文件 - 因此(我认为)不会记录任何内容。
由于目标应该是微服务,我使用的是 CQRS 模式。
这是我的 Startup.cs
private readonly ISession session;
private readonly ILogger logger;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
var baseDirectory = Directory.GetDirectoryRoot(AppDomain.CurrentDomain.BaseDirectory);
Log.Logger = new LoggerConfiguration()
.WriteTo
.Logger(lc => lc.Filter
.ByIncludingOnly(e => e.Level == LogEventLevel.Information || e.Level == LogEventLevel.Debug)
.WriteTo.RollingFile(Path.Combine(baseDirectory, "/Logs/info.log")))
.WriteTo
.Logger(lc => lc.Filter
.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
.WriteTo.RollingFile(Path.Combine(baseDirectory, "/Logs/error.log")))
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
loggerFactory.AddSerilog();
...//To shorten this example in Stackoverflow, I've excluded the standard code. But in reality they are of course there
}
这是我的类,其中记录器将由 DI 注入(inject):
public MaterialCommandHandler(ISession session, ILogger<MaterialCommandHandler> logger)
{
this.session = session;
this.logger = logger;
}
以及位于 MaterialCommandHandler 类中的 Handle 方法,我想在其中向日志文件中写入一些内容
public async Task Handle(CreateMaterialCommand command)
{
var material = new Material(command.Id, command.TechDesc, command.Description, command.MaterialClass);
logger.LogDebug($"{DateTimeOffset.UtcNow} - {nameof(CreateMaterialCommand)} - received for {material} with {nameof(command.TechDesc)} : {command.TechDesc}.");
await session.Add(material);
await session.Commit();
logger.LogDebug($"{DateTimeOffset.UtcNow} - {nameof(CreateMaterialCommand)} - received for {material} with {nameof(command.TechDesc)} : {command.TechDesc}.");
}
任何人都知道为什么没有创建文件 - 并且不会记录任何内容?
最佳答案
您错过了 .CreateLogger()
您的日志构建结束时的声明,但我认为真正的问题是您的 Path.Combine
语句可能导致无效路径或您不期望的路径。 Path.Combine
有一些您可能不知道的烦人行为。考虑以下:
Path.Combine(@"C:\Temp", @"Logs\mylog.txt"); // C:\Temp\Logs\mylog.txt
Path.Combine(@"C:\Temp\", @"Logs\mylog.txt"); // C:\Temp\Logs\mylog.txt
Path.Combine(@"C:\Temp\", @"\Logs\mylog.txt"); // \Logs\mylog.txt
Path.Combine(@"C:\Temp", @"\Logs\mylog.txt"); // \Logs\mylog.txt
关于c# - Serilog 不创建日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49051609/