【问题标题】:NLog Console logging on single lineNLog 控制台单行日志记录
【发布时间】:2015-11-25 10:32:55
【问题描述】:

我希望能够显示日志消息,例如单个控制台行中的跟踪级别,而不是将它们堆叠在一起。

应在控制台中显示一条 Trace 日志消息,然后在同一行上替换为另一条 Trace 日志消息。 当另一个日志消息进来时,例如警告,消息堆栈应照常继续。

有没有办法为 NLog 中的控制台日志定义这种单行覆盖?

【问题讨论】:

    标签: .net logging nlog


    【解决方案1】:

    如果你包装 NLog,这似乎可以工作

    public class Logger : NLog.Logger
    {
        public void TraceStackConsole(string message)
        {
            this.Trace(message);
            Console.SetCursorPosition(0, Console.CursorTop-1);
        }
    }
    

    你也可以通过https://github.com/NLog/NLog/wiki/Replace-NewLines-Layout-Renderer 获得一些有趣的结果,尽管我还没有成功。用“\r”替换它可能会起作用

    How can I update the current line in a C# Windows Console App? "如果你只打印"\r"到控制台,光标会回到当前行的开头,然后你可以重写它。"

    【讨论】:

    • 非常感谢您的回答。我会尝试并尽快回来。
    【解决方案2】:

    非常感谢@alexbezek,这正是我想要的! :)

    虽然我认为为记录器制作扩展方法对我来说更方便:

    public static class LoggerExtension
    {
        public static void ConsoleStack(this Logger logger, string message)
        {
            logger.Trace(message);
            Console.SetCursorPosition(0, Console.CursorTop-1);
        }
    }
    

    那么我可以这样称呼它:Logger.ConsoleStack("Log message");

    【讨论】:

      最近更新 更多