简单的方法,但会对性能产生影响(注意
${mdlc:item=module}
区分大小写)
public static void LogInfoWithModule<T>(this ILogger<T> logger, string message, string module)
{
using (logger.BeginScope(new [] { new KeyValuePair<string,object>("module", module) }))
{
logger.Log(LogLevel.Information, message);
}
}
这个
advanced way for injecting properties
(通知
${event-properties:module}
区分大小写):
public static void LogInfoWithModule<T>(this ILogger<T> logger, string message, string module)
{
logger.Log(LogLevel.Information, default(EventId), new ModuleLogEvent(message, module), default(Exception), ModuleLogEvent.Formatter);
}
class ModuleLogEvent : IReadOnlyList<KeyValuePair<string, object>>
{
public static Func<ModuleLogEvent, Exception, string> Formatter { get; } = (l, ex) => l.Message;
public string Message { get; }
public string Module { get; }
public MyLogEvent(string message, string module)
{
Message = message;
Module = module;
}
public override string ToString() => Message;
// IReadOnlyList-interface
public int Count => 1;
public KeyValuePair<string, object> this[int index] => new KeyValuePair<string,object>("module", Module);
public IEnumerator<KeyValuePair<string, object>> GetEnumerator() => yield return new KeyValuePair<string,object>("module", Module);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
请注意,上述示例代码中可能包含拼写错误和编译错误。
你可能会在这里找到幸福:
https://github.com/viktor-nikolaev/XeonApps.Extensions.Logging.WithProperty
:
public static class LoggingExtensions
{
public static NLog.Logger WithModule(this NLog.Logger logger, object propertyValue) =>
logger.WithProperty("module", propertyValue);
public static ILogger WithModule(this ILogger logger, object propertyValue) =>
logger.WithProperty("module", propertyValue);
}