I want to print log to file from my system (.NET Framework 4.6.1) I want to print this information: className, methodName, lineNumber from which log entry was Called.
I've a Serilog class: `
public class SerilogClass
{
public static readonly ILogger _log;
static SerilogClass()
{
string logsFolder = ConfigurationManager.AppSettings["logsFolder"];
string environment = ConfigurationManager.AppSettings["environment"];
_log = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File(logsFolder + "//" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".log", outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:Ij}{NewLine}{Exception}")
.CreateLogger();
}
}
I'm trying to document the system with logs:
public class MyClass
{
private readonly ILogger _log = SerilogClass._log;
public void GetData()
{
_log.information("run GetData, **here I want to print by default the class path and the line number**")
}
}
What should I add in SerilogClass? I would be happy to advices. Thanks.
To automatically log the class name, method name, and line number in Serilog, you can use the Serilog.Enrichers.StackTrace NuGet package.
Below is an example of how a log entry might look when using Serilog configured with the Serilog.Enrichers.StackTrace:
To automatically log the class name, method name, and line number without the need for external packages like
Serilog.Enrichers.StackTrace
as Blindy said, you can use the compiler services features provided by C# such asCallerMemberName
,CallerFilePath
, andCallerLineNumber
.Example: