开发者

How can I implement a TextWriter in order to append a timestamp to each line writen to the console?

开发者 https://www.devze.com 2023-04-12 09:48 出处:网络
My apologies if this has already been answered, I\'ve tried my best to look. I have a library that writes some information to the console.In the application that uses the library, I\'d like to redire

My apologies if this has already been answered, I've tried my best to look.

I have a library that writes some information to the console. In the application that uses the library, I'd like to redirect that output to a control as well as a log file, while writing a timestamp at the beginning of each line. This is what my class looks like:

class TextBoxStreamWriter : Te开发者_如何学运维xtWriter
{
    TextBox _output;
    FileStream _stream;
    StreamWriter _writer;

    // constructor
    public TextBoxStreamWriter(TextBox output)
    {
        _output = output;

        _stream = new FileStream(@"C:\example.log", FileMode.OpenOrCreate, FileAccess.Write);
        _writer = new StreamWriter(_stream);
        _writer.AutoFlush = true;
    }

    // override methods
    public override void Write(char value)
    {
        base.Write(value);
        _output.AppendText(value.ToString());
        _writer.Write(value);
    }
    public override void WriteLine(string value)
    {
        base.WriteLine(DateTime.Now.ToString("[yyyy/MM/dd HH:mm:ss]\t") + value);
    }

This seems to work fine as long as you're using Console.WriteLine() of course. But we I try to direct the output of an XMLWriter to the console, this bypasses Console.WriteLine(), and thereby starts printing lines without the timestamp. One example could be this:

    protected void WriteXMLToConsole(XmlDocument xmlDocument)
    {
        XmlTextWriter writer = new XmlTextWriter(Console.Out);
        writer.Formatting = Formatting.Indented;
        xmlDocument.WriteContentTo(writer);
        writer.Flush();
        Console.WriteLine();
    }

Any suggestions?

Thanks for your help!


It's probably because the xmlDoc is recieved as a single string containing NewLine.
Try reading the xmlDoc as a plain text-file, and sendt that text to console line-by-line

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号