将console.writeLine()消息传递到文本文件 [英] Pipe console.writeLine() messages to a text file
问题描述
我想知道实现记录器的最佳方法是什么,该记录器实际上会吃掉所有 Console.WriteLine()
消息并吐出所有这些消息的文本文件。
I wonder what the best approach is in implementing a logger which essentially eats all Console.WriteLine()
messages and spits out a text file of all these messages.
我知道我可以使用 StringBuilder
并通过执行用所有消息填充它。
出现 Console.WriteLine
的任何地方...但是我正在寻找比这更神奇的东西。通过某种方式,我不必编写与现有代码中的 Console.WriteLine
s一样多的代码行。
I know I could use a StringBuilder
and populate it with all the messages by doing .AppendLine
wherever Console.WriteLine
occurs...but I am looking for something more magical than that. Some way using which I don't have to write as many lines of code as Console.WriteLine
s in existing code.
如果您错过了标签,这是针对C#4.0控制台应用程序的。
And in case you missed the tags, this is for a C#4.0 console application.
推荐答案
我假设您是want是写入标准输出和文件的流。也就是说,您希望所有内容仍显示在控制台上,但是您还希望将其写入文件中。 (如果只想将输出重定向到文件,则可以从命令行执行。)
I assume what you want is a stream that writes to standard out and to a file. That is, you want everything to still show up on the console, but you also want it to be written to a file. (If you just wanted to redirect output to a file, you could do that from the command line.)
您需要创建自己的 TextWriter
派生的类,并使其实际输出。您调用 Console.SetOut
使控制台写入您的 TextWriter
。
You need to create your own TextWriter
-derived class, and have it do the actual output. You call Console.SetOut
to make the console write to your TextWriter
.
class ConsoleLogger: TextWriter
{
private TextWriter ConsoleOutputStream;
private StreamWriter LogOutputStream;
public ConsoleLogger(string logFilename)
{
ConsoleOutputStream = Console.Out;
// Initialize your log file
LogOutputStream = new StreamWriter(logFilename);
}
public void Write(string s)
{
ConsoleOutputStream.Write(s);
LogOutputStream.Write(s);
}
// Other Write functions format their arguments and call Write(string).
}
在使用此功能的程序中:
And in the program that uses this:
private ConsoleLogger MyLogger;
const string LogFilename = "ConsoleLog.txt";
void Main()
{
MyLogger = new ConsoleLogger(LogFilename);
Console.SetOut(MyLogger);
}
您不必覆盖所有 TextWriter
方法。正如文档所述,派生类必须至少实现 TextWriter.Write(Char)
方法以创建 TextWriter
的有用实例。
You don't have to override all the TextWriter
methods. As the documentation says, "A derived class must minimally implement the TextWriter.Write(Char)
method to make a useful instance of TextWriter
."
我做了类似的事情,并且效果很好。
I've done something similar to this, and it works quite well.
这篇关于将console.writeLine()消息传递到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!