-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathILoggerExtensions.cs
38 lines (36 loc) · 1.95 KB
/
ILoggerExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging;
namespace Utils.DotNetCore.ILogger.Extensions
{
public static class ILoggerExtensions
{
/// <summary>
/// Log message with class, method names and line number
/// </summary>
/// <param name="logger"></param>
/// <param name="logLevel"></param>
/// <param name="message"></param>
/// <param name="memberName"></param>
/// <param name="sourceFilePath"></param>
/// <param name="sourceLineNumber"></param>
public static void LogWithContext(this Microsoft.Extensions.Logging.ILogger logger, LogLevel logLevel, string? message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
{
var className = Path.GetFileNameWithoutExtension(sourceFilePath);
logger.Log(logLevel, "{Message} (at {ClassName}.{MethodName}, line {LineNumber})", message, className, memberName, sourceLineNumber);
}
/// <summary>
/// Log message about exception with class, method names and line number
/// </summary>
/// <param name="logger"></param>
/// <param name="message"></param>
/// <param name="ex"></param>
/// <param name="memberName"></param>
/// <param name="sourceFilePath"></param>
/// <param name="sourceLineNumber"></param>
public static void LogExceptionWithContext(this Microsoft.Extensions.Logging.ILogger logger, string? message, Exception? ex = null, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
{
var className = Path.GetFileNameWithoutExtension(sourceFilePath);
logger.Log(LogLevel.Error, ex, "{Message} (at {ClassName}.{MethodName}, line {LineNumber})", message, className, memberName, sourceLineNumber);
}
}
}