我想使用日志范围关联日志消息。我正在寻找 log4net、NLog 或 System.Diagnostics.Trace 的实现。下面是演示该概念的基本实现。程序的输出如下:
First level: Logging in the run method
First level: Logging one level down
Second scope: Another message
First level: Back from scope
下面所做的事情是否有更强大/通用/经过验证/易于与某些框架一起使用的版本?
class Program
{
private static readonly Log Log = new Log();
private static void Main()
{
using (new LoggingScope("First level"))
{
Run();
}
}
private static void Run()
{
Log.Info("Logging in the run method");
Run2();
}
private static void Run2()
{
Log.Info("Logging one level down");
using (new LoggingScope("Second scope"))
{
Log.Info("Another message");
}
Log.Info("Back from scope");
}
}
internal class Log
{
static Log()
{
CurrentScope = new Stack<string>();
}
private static Stack<string> CurrentScope { get; set; }
public static void PushScope(string name)
{
CurrentScope.Push(name);
}
public static void PopScope()
{
CurrentScope.Pop();
}
public void Info(string message)
{
var currentScope = CurrentScope.Count == 0 ? string.Empty : CurrentScope.Peek();
Console.WriteLine("{0}: {1}", currentScope, message);
}
}
internal class LoggingScope : IDisposable
{
private readonly string _name;
public LoggingScope(string id)
{
_name = Guid.NewGuid().ToString();
Log.PushScope(id);
CallContext.SetData(_name, id);
}
public void Dispose()
{
Log.PopScope();
CallContext.FreeNamedDataSlot(_name);
}
}
最佳答案
您正在寻找嵌套诊断上下文 (NDC):
Log.Info("Logging one level down");
using(ThreadContext.Stacks["NDC"].Push( requestid))
{
Log.Info("Another message");
}
Log.Info("Back from scope");
要获取日志输出的范围,请在转换模式中使用 %property{NDC}:
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
关于c# - 关联范围内的日志消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27401753/