我最近为我的ASP.Net Core项目添加了日志记录。目前,日志以以下格式写入.txt文件:
{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}
例如:
2017-11-30 13:58:22.229 +01:00 [Information] Item created in database.
虽然这很好,但我想要在.txt文件中看到记录日志的类名和正在执行的方法名称。例如,当A类使用B方法向数据库写入内容并记录时,我想看到像这样的东西:
ClassA.MethodB:Item created in database
所有记录日志的类都在它们的构造函数中注入Logger。
public class ClassA
{
private readonly ILogger _log;
public ClassA(ILogger<ClassA> log){
_log = log;
}
public void AddItemToDb(Item item){
//Add item
//On success:
_log.LogInfo("Added item to db.");
}
}
我目前正在使用Serilog,并使用以下的LoggerConfiguration:
var logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.WriteTo.RollingFile(Configuration.GetValue<string>("LogFilePath") + "-{Date}.txt", LogEventLevel.Information)
.CreateLogger();
如何在我的日志中添加类和方法?
编辑
我像这样向.WriteTo.Rollingfile()方法添加了一个自定义的outputTemplate:
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}) {Message}{NewLine}{Exception}")
这导致命名空间和类被添加到日志中,现在只缺少方法。
ILogger
是什么类型?它是 Serilog 记录器吗?还是 ASP.NET Core 记录器? - mason