using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Implab.Diagnostics { public abstract class TextListenerBase : ServiceLocator, IEventTextFormatter, IEventTextFormatter { readonly Dictionary m_subscriptions = new Dictionary(); readonly LogicalOperation m_boundOperation; readonly int m_baseIndent; protected TextListenerBase(bool global) { Register(this); if (!global) { m_boundOperation = TraceContext.Instance.CurrentOperation; m_baseIndent = Math.Max(0, m_boundOperation.Level - 1); } } public void Subscribe(Type eventType) { if (eventType == null) throw new ArgumentNullException("eventType"); GetType().GetMethod("Subscribe", new Type[0]).MakeGenericMethod(eventType).Invoke(this, null); } public void Subscribe() { Subscribe(LogChannel.Default); } public void Subscribe(LogChannel channel) { if (channel == null) throw new ArgumentNullException("channel"); lock (m_subscriptions) { AssertNotDisposed(); var formatter = GetService>(); var channelName = channel.Name; EventHandler> handler = (sender, args) => { var text = formatter.Format(args, args.Value); text.indent -= m_baseIndent; if (IsRelated(args.Operation)) WriteEntry(args, text, channelName); }; if (m_subscriptions.ContainsKey(channel)) return; channel.Events += handler; Action unsubscribe = () => { channel.Events -= handler; }; m_subscriptions.Add(channel, unsubscribe); } } public bool IsRelated(LogicalOperation op) { if (m_boundOperation == null) return true; while (op != m_boundOperation && op.Level > m_boundOperation.Level) op = op.Parent; return op == m_boundOperation; } public void Unsubscribe(LogChannel channel) { if (channel == null) throw new ArgumentNullException("channel"); lock (m_subscriptions) { Action subscription; if (m_subscriptions.TryGetValue(channel, out subscription)) { subscription(); m_subscriptions.Remove(channel); } } } public void UnsubscribeAll() { lock (m_subscriptions) { foreach (var subscription in m_subscriptions.Values) subscription(); m_subscriptions.Clear(); } } /// /// Вызывается для записи текста сообщения, в журнал. /// /// /// Данный метод может вызваться из разных потоков одновременно. Возможна ситуация, когда /// данный метод вызывается уже после освобождения ообъекта методом . /// /// Текст сообщения. /// protected abstract void WriteEntry(LogEventArgs args, EventText text, string channel); public EventText Format(LogEventArgs args, object data) { return new EventText { indent = args.Operation.Level, content = data.ToString() }; } public EventText Format(LogEventArgs args, TraceEvent data) { var level = args.Operation.Level; if (data.EventType == TraceEventType.OperationCompleted || data.EventType == TraceEventType.OperationStarted) level--; return new EventText { indent = level, content = data.ToString() }; } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { UnsubscribeAll(); } } } }