ConsoleTraceListener.cs
37 lines
| 1.1 KiB
| text/x-csharp
|
CSharpLexer
cin
|
r36 | 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()); | ||||
} | ||||
} | ||||
} | ||||
} | ||||