有没有一种方法来Console.Write的结果连续镜像到一个集合(数组,列表等)? [英] Is there a way to continuously mirror the result of Console.Write to a collection (array,list,etc)?
问题描述
我有一个控制台程序,我想Console.Write的结果连续镜像到一个集合,我可以看看在实时尾巴。集合可以是阵列,列表,等等。
I have a console program, I'd like to continuously mirror the result of Console.Write to a collection, which I can look at the tail of in real time. The collection could be an array, a list, etc.
我想我不得不使用某种事件处理的?
I assume I'd have to use some sort of event handler?
我不介意被指向的第三方库,如方向NLOG。
I don't mind being pointed in the direction of a 3rd party library, e.g. NLog.
更新
我需要保持在内存中的集合,它反映了当前控制台状态(然后我就可以发送到使用套接字远程WinForms应用程序)。详细信息之外,我想我可以用C#的几行做到这一点 - 我不希望添加一个巨大的日志库没有好的需要它
I need to maintain a collection in memory, which mirrors the current console state (I can then send to a remote WinForms app using sockets). Details aside, I think I can do this with a few lines of C# - I don't want to add a huge logging library without a good need for it.
推荐答案
控制台类可以更换输出和错误流。究竟是什么,你需要在这里,你可以用的TextWriter也记录写的是什么取代他们。示例实现:
The Console class allows you to replace the output and error streams. Just what you need here, you can replace them with a TextWriter that also logs what is written. A sample implementation:
class ConsoleLogger : System.IO.TextWriter {
private System.IO.TextWriter oldOut;
private Queue<string> log = new Queue<string>();
private StringBuilder line = new StringBuilder();
private object locker = new object();
private int newline;
private int logmax;
public ConsoleLogger(int history) {
logmax = history;
oldOut = Console.Out;
Console.SetOut(this);
}
public override Encoding Encoding {
get { return oldOut.Encoding; }
}
public override void Write(char value) {
oldOut.Write(value);
lock (locker) {
if (value == '\r') newline++;
else if (value == '\n') {
log.Enqueue(line.ToString());
if (log.Count > logmax) log.Dequeue();
line.Length = newline = 0;
}
else {
for (; newline > 0; newline--) line.Append('\r');
line.Append(value);
}
}
}
}
用法:
static void Main(string[] args) {
var outLogger = new ConsoleLogger(100);
// etc...
}
这篇关于有没有一种方法来Console.Write的结果连续镜像到一个集合(数组,列表等)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!