view Implab/Diagnostics/TextFileListener.cs @ 216:1e082fb67a46 v2

Fixed component container
author cin
date Tue, 25 Apr 2017 19:51:33 +0300
parents 8200ab154c8a
children 6efb77590b15
line wrap: on
line source

using System;
using System.IO;
using System.Text;

namespace Implab.Diagnostics {
    public class TextFileListener: ListenerBase {
        readonly TextWriter m_textWriter;
        readonly object m_lock = new object();

        public TextFileListener(string fileName) {
            m_textWriter = File.CreateText(fileName);

            m_textWriter.WriteLine("LOG {0}", DateTime.Now);
        }

        #region implemented abstract members of ListenerBase

        public override void Write(LogEventArgs args, object entry) {
            var msg = new StringBuilder();
            for (int i = 0; i < args.Operation.Level; i++)
                msg.Append("  ");
            msg.AppendFormat("[{0}]:{1}: {2}", args.ThreadId, args.Channel, entry);

            lock (m_lock) {
                if (!IsDisposed) {
                    // тут гарантировано еще не освобожден m_textWriter
                    m_textWriter.WriteLine(msg);
                    m_textWriter.Flush();
                }
            }
        }

        #endregion

        protected override void Dispose(bool disposing) {
            base.Dispose(disposing);
            if (disposing) {
                // IsDisposed = true
                lock (m_lock) {
                    Safe.Dispose(m_textWriter);
                }
            }
        }

        
    }
}