c# - 关联范围内的日志消息

标签 c# log4net trace nlog

我想使用日志范围关联日志消息。我正在寻找 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" />

log4net.ThreadContext.Stacks (404)

log4net.NDC (deprecated) (404)

关于c# - 关联范围内的日志消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27401753/

相关文章:

c# - ConnectionStrings 或 AppSettings 的存储库

java - 将 curl 调用转换为 java urlconnection 调用

log4net - 如何为控制台输出设置 DEBUG,为 FileAppender 设置 INFO?

c# - 如何使用 `System.Diags...Trace` 以详细级别登录

linux - 在Linux中追踪进程需要什么样的权限

c# - 程序集在不应该的时候被复制到本地

c# - 读取从ASMX返回的JSON数据

c# - 开发 Windows Phone 8、SQL Server Express 或 SQL Server Compact 或 SQLite 时最好使用什么?

log4net - 限制来自 smtpappender (log4Net) 的电子邮件

c# - 如何消除 log4net 中的重复日志记录?