Бих искал да свържа регистрираните съобщения с помощта на обхват на регистриране. Търся реализация за 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);
}
}