C#ASP.NET Core Serilog添加类名和方法进行记录 [英] C# ASP.NET Core Serilog add class name and method to log
问题描述
我最近将日志记录添加到了ASP.Net Core项目中.当前,日志以以下格式写入.txt文件:
I recently added logging to my ASP.Net Core project. Currently the log writes to a .txt file in this format:
{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message} {NewLine} {Exception}
{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}
例如:
2017-11-30 13:58:22.229 +01:00 [信息]在数据库中创建的项目.
2017-11-30 13:58:22.229 +01:00 [Information] Item created in database.
这很好,但是我想输入要记录到该.txt文件的类的名称和方法.例如,当A类使用方法B向数据库中写入内容并将其记录下来时,我希望看到类似
This is fine but I would like to have the name of the class that logs and the method that is being executed to this .txt file. For example when Class A writes something to the database using Method B and logs this, I would like to see something like
ClassA.MethodB:在数据库中创建的项
ClassA.MethodB: Item created in database
所有记录日志的类都将其Logger注入到其构造函数中,例如
All the classes that log have their Logger injected into their constructors like
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:
I'm currently using Serilog and using the following LoggerConfiguration:
var logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.WriteTo.RollingFile(Configuration.GetValue<string>("LogFilePath") + "-{Date}.txt", LogEventLevel.Information)
.CreateLogger();
如何将类和方法添加到日志中?
How can I add the class and method to my logs?
修改
我向.WriteTo.Rollingfile()方法中添加了一个自定义outputTemplate,如下所示:
I added a custom outputTemplate to the .WriteTo.Rollingfile() method like so:
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}) {Message}{NewLine}{Exception}")
导致在日志中添加名称空间和类的原因,只是现在缺少该方法
Which resulted in the namespace plus the class to be added in the log, only the method is missing now
推荐答案
I solved this issue by using a combination of Jordan's answer and this answer.
我通过通过 enrichment 添加logcontext来更改Logger配置,我在我的outputTemplate中添加了属性"method":
I changed my Loggerconfiguration by adding the logcontext through enrichment and I added the property 'method' to my outputTemplate:
var logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.RollingFile(Configuration.GetValue<string>("LogFilePath") + "-{Date}.txt", LogEventLevel.Information,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{Method}) {Message}{NewLine}{Exception}")
.CreateLogger();
Enrich.FromLogContext允许使用LogContext.PushProperty()方法将属性推送到outputTemplate.在这种情况下,请使用'method'属性(请注意outputTemplate中的{Method}).
The Enrich.FromLogContext enables properties to be pushed to the outputTemplate by using the LogContext.PushProperty() method. In this case for the 'method' property (notice the {Method} in the outputTemplate).
异步方法的示例:
using (LogContext.PushProperty("Method", new LogAsyncMethods().GetActualAsyncMethodName()))
{
_log.LogInformation("Log message.");
}
GetActualAsyncMethodName()的编写方式如下:
Where GetActualAsyncMethodName() is written like this:
public static string GetActualAsyncMethodName([CallerMemberName]string name = null) => name;
这对于 async 方法很有效.
现在使用非异步方法可以正常工作:
Now for non-async methods this works fine:
using (LogContext.PushProperty("Method", System.Reflection.MethodBase.GetCurrentMethod().Name))
{
_log.LogInformation("Changing of customer name succeeded");
}
现在方法名称正在日志记录中显示. SourceContext添加名称空间+类,并通过添加.{Method}"将导致:
Now the method name is being displayed in the logging. The SourceContext adds the namespace + the class and by adding ".{Method}" it will result in:
Namespace.ClassName.MethodName
Namespace.ClassName.MethodName
这篇关于C#ASP.NET Core Serilog添加类名和方法进行记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!