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?
I don't mind being pointed in the direction of a 3rd party library, e.g. NLog.
Update
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.
Skip(1)) { String[] token = r. Split(','); String[] datetime = token[0]. Split(' '); String timeText = datetime[4]; String actions = token[2]; Console. WriteLine("The time for this array is: " + timeText); Console.
WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.
In C# you can write or print to console using Console. WriteLine() or Console. Write(), basically both methods are used to print output of console.
Console. WriteLine writes your output to the console window opened by your application (think black window with white text that appears when you open the Command Prompt.) Try System. Diagnostics.
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);
}
}
}
}
Usage:
static void Main(string[] args) {
var outLogger = new ConsoleLogger(100);
// etc...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With