view Implab/Diagnostics/ConsoleTraceListener.cs @ 38:1cedc4e58acc diagnostics

Закрыть ветку diagnostics
author cin
date Tue, 15 Apr 2014 02:46:33 +0400
parents 313f708a50e9
children fe33f4e02ad5
line wrap: on
line source

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Implab.Diagnostics {
    public class ConsoleTraceListener {

        static readonly object _consoleLock = new object();

        public void Subscribe() {
            LogChannel<TraceEvent>.Default.Events += Default_Events;
        }

        public void Unsubscribe() {
            LogChannel<TraceEvent>.Default.Events -= Default_Events;
        }

        void Default_Events(object sender, ValueEventArgs<TraceEvent> e) {
            LogEvent((TraceContext)sender, e.Value);
        }

        void LogEvent(TraceContext context, TraceEvent evt) {
            var msg = new StringBuilder();
            for (int i = 0; i < context.CurrentOperation.Level; i++)
                msg.Append("  ");
            msg.Append(evt.EventType);
            msg.AppendFormat("[{0}]: ",context.ThreadId);
            msg.Append(evt.Message);

            lock (_consoleLock) {
                Console.ForegroundColor = (ConsoleColor)(context.ThreadId % 15 + 1);
                Console.WriteLine(msg.ToString());
            }
        }
    }
}