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 进行注入:
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()
的调用。而且,为了测试认证\权限问题,最好在日志文件夹上赋予“Everyone”修改权限(仅限测试)。 - SpruceMoose