将控制台输出镜像到文件

xyz*_*xyz 86 .net c# console text file

在C#控制台应用程序中,是否有一种智能方法可以将控制台输出镜像到文本文件中?

目前我只是将相同的字符串传递给两个Console.WriteLineInstanceOfStreamWriter.WriteLine一个日志方法.

Oli*_*ich 113

这可能是一些更多的工作,但我会反过来.

TraceListener为控制台实例化一个,为日志文件实例化一个; 之后Trace.Write在代码中使用语句而不是Console.Write.之后删除日志或控制台输出或附加其他日志记录机制变得更加容易.

static void Main(string[] args)
{
    Trace.Listeners.Clear();

    TextWriterTraceListener twtl = new TextWriterTraceListener(Path.Combine(Path.GetTempPath(), AppDomain.CurrentDomain.FriendlyName));
    twtl.Name = "TextLogger";
    twtl.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime;

    ConsoleTraceListener ctl = new ConsoleTraceListener(false);
    ctl.TraceOutputOptions = TraceOptions.DateTime;

    Trace.Listeners.Add(twtl);
    Trace.Listeners.Add(ctl);
    Trace.AutoFlush = true;

    Trace.WriteLine("The first line to be in the logfile and on the console.");
}
Run Code Online (Sandbox Code Playgroud)

据我所知,您可以在应用程序配置中定义侦听器,从而可以在不触及构建的情况下激活或停用日志记录.

  • 我真的很喜欢这个解决方案,所以我做了一个关于它的快速博客,并进行了一些小小的清理工作以及沿途的一些障碍.http://www.mcrook.com/2014/11/quick-and-easy-console-logging-trace.html感谢您的出色解决方案:) (5认同)
  • 那是完美的 - 谢谢.我知道Log4Net,但是必须为这样的东西拉入库似乎是错误的. (4认同)
  • 我不知道为什么他们没有做大量的跟踪 - 在我看来,它应该适用于生产规模的日志记录,但是每个人都希望使用额外的库(如log4net)来实现它. (3认同)

Chr*_*ian 48

这是一个简单的类,它将TextWriter子类化,以允许将输入重定向到文件和控制台.

像这样使用它

  using (var cc = new ConsoleCopy("mylogfile.txt"))
  {
    Console.WriteLine("testing 1-2-3");
    Console.WriteLine("testing 4-5-6");
    Console.ReadKey();
  }
Run Code Online (Sandbox Code Playgroud)

这是班级:

class ConsoleCopy : IDisposable
{

  FileStream fileStream;
  StreamWriter fileWriter;
  TextWriter doubleWriter;
  TextWriter oldOut;

  class DoubleWriter : TextWriter
  {

    TextWriter one;
    TextWriter two;

    public DoubleWriter(TextWriter one, TextWriter two)
    {
      this.one = one;
      this.two = two;
    }

    public override Encoding Encoding
    {
      get { return one.Encoding; }
    }

    public override void Flush()
    {
      one.Flush();
      two.Flush();
    }

    public override void Write(char value)
    {
      one.Write(value);
      two.Write(value);
    }

  }

  public ConsoleCopy(string path)
  {
    oldOut = Console.Out;

    try
    {
      fileStream = File.Create(path);

      fileWriter = new StreamWriter(fileStream);
      fileWriter.AutoFlush = true;

      doubleWriter = new DoubleWriter(fileWriter, oldOut);
    }
    catch (Exception e)
    {
      Console.WriteLine("Cannot open file for writing");
      Console.WriteLine(e.Message);
      return;
    }
    Console.SetOut(doubleWriter);
  }

  public void Dispose()
  {
    Console.SetOut(oldOut);
    if (fileWriter != null)
    {
      fileWriter.Flush();
      fileWriter.Close();
      fileWriter = null;
    }
    if (fileStream != null)
    {
      fileStream.Close();
      fileStream = null;
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是最完整的解决方案.不需要覆盖Write/WriteLine方法的所有重载,并且对其他代码是透明的.因此,所有控制台活动都将复制到文件中,而不会对其他代码进行任何更改. (5认同)
  • 谢啦!这很棒!我刚刚用*File.Open(path,FileMode.Append,FileAccess.Write,FileShare.Read)替换了*File.Create*;*因为我不想在启动时删除旧日志而我希望能够打开日志程序仍在运行时的文件. (3认同)

tva*_*son 13

查看log4net.使用log4net,您可以设置控制台和文件追加器,它们可以使用单个日志语句将日志消息输出到两个位置.

  • 好吧,我认为如果可以用已有的库来完成,应该避免使用额外的库. (6认同)

xto*_*ofl 9

您不能使用>命令将输出重定向到文件吗?

c:\>Console.exe > c:/temp/output.txt
Run Code Online (Sandbox Code Playgroud)

如果需要镜像,可以尝试查找tee将输出拆分为文件的win32版本.

  • 我需要镜像.这就是它在主题和身体中被提及的原因.谢谢你的提示:) (8认同)

aru*_*rul 8

您可以继承TextWriter类,然后使用Console.SetOut方法将其实例分配给Console.Out - 这尤其与将相同的字符串传递给log方法中的两个方法相同.

另一种方法可能是声明您自己的Console类并使用using语句来区分类:

using Console = My.Very.Own.Little.Console;
Run Code Online (Sandbox Code Playgroud)

要访问标准控制台,您需要:

global::Console.Whatever
Run Code Online (Sandbox Code Playgroud)


Kee*_*ing 8

正如我从这里学到的那样,真的需要在这里分享我的解决方案.

首先,我们需要创建StreamWriter固有的新类,比如CombinedWriter;

然后使用Console.Out初始化CombinedWriter的新瞬间;

最后,我们可以通过Console.SetOut将控制台输出重定向到新类的瞬间;

以下代码是新课程适合我.

public class CombinedWriter : StreamWriter
{
    TextWriter console;
    public CombinedWriter(string path, bool append, Encoding encoding, int bufferSize, TextWriter console)
        :base(path, append, encoding, bufferSize)
    {
        this.console = console;
        base.AutoFlush = true; // thanks for @konoplinovich reminding
    }
    public override void WriteLine(string value)
    {
        console.Write(value);
        base.WriteLine(value);
    }
}
Run Code Online (Sandbox Code Playgroud)


kgi*_*kis 6

Log4net可以为您完成此操作.你只会写这样的东西:

logger.info("Message");
Run Code Online (Sandbox Code Playgroud)

配置将确定打印输出是否将转到控制台,文件或两者.


Ric*_*Wit 5

我认为您已经在使用的是最好的方法。一种从本质上镜像输出的简单方法。

首先在开头声明一个全局TextWriter:

private TextWriter txtMirror = new StreamWriter("mirror.txt");
Run Code Online (Sandbox Code Playgroud)

然后制定一个写法:

// Write empty line
private void Log()
{
    Console.WriteLine();
    txtMirror.WriteLine();
}

// Write text
private void Log(string strText)
{
    Console.WriteLine(strText);
    txtMirror.WriteLine(strText);
}
Run Code Online (Sandbox Code Playgroud)

现在,不要使用Console.WriteLine("...");,而是使用Log("...");。就那么简单。它甚至更短!


如果您移动光标位置 ( Console.SetCursorPosition(x, y);)可能会有些麻烦,但其他方面效果很好,我自己也使用它!

编辑

当然,Console.Write();如果您不只使用 WriteLines,您可以以相同的方式制作方法