#region License Information /* HeuristicLab * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL) * * This file is part of HeuristicLab. * * HeuristicLab is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HeuristicLab is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HeuristicLab. If not, see . */ #endregion using System; using System.Collections.Concurrent; using System.Collections.Generic; using HeuristicLab.Common; using HeuristicLab.Persistence; namespace HeuristicLab.Core { [Item("ThreadSafeLog", "A thread-safe log for logging string messages.")] [StorableType("0f729d7c-8d01-4297-8793-ed1524d360a1")] public sealed class ThreadSafeLog : Item, ILog, IStorableContent { public string Filename { get; set; } private ConcurrentQueue messages; public IEnumerable Messages { get { return messages.ToArray(); } } [Storable(Name = "messages")] private IEnumerable StorableMessages { get { return Messages; } set { messages = new ConcurrentQueue(value); } } [Storable] private long maxMessageCount; public long MaxMessageCount { get { return maxMessageCount; } } [StorableConstructor] private ThreadSafeLog(StorableConstructorFlag deserializing) : base(deserializing) { } private ThreadSafeLog(ThreadSafeLog original, Cloner cloner) : base(original, cloner) { this.messages = new ConcurrentQueue(original.messages); this.maxMessageCount = original.maxMessageCount; } public ThreadSafeLog(long maxMessageCount = int.MaxValue) { this.messages = new ConcurrentQueue(); this.maxMessageCount = maxMessageCount; } public override IDeepCloneable Clone(Cloner cloner) { return new ThreadSafeLog(this, cloner); } public void Clear() { messages = new ConcurrentQueue(); OnCleared(); } public void LogMessage(string message) { var s = Log.FormatLogMessage(message); messages.Enqueue(s); CapMessages(); OnMessageAdded(s); } public void LogException(Exception ex) { var s = Log.FormatException(ex); messages.Enqueue(s); CapMessages(); OnMessageAdded(s); } private readonly object capLock = new object(); private void CapMessages() { lock (capLock) { string s; while (messages.Count > maxMessageCount) if (!messages.TryDequeue(out s)) break; } } public event EventHandler> MessageAdded; private void OnMessageAdded(string message) { var handler = MessageAdded; if (handler != null) handler(this, new EventArgs(message)); } public event EventHandler Cleared; private void OnCleared() { var handler = Cleared; if (handler != null) handler(this, EventArgs.Empty); } } }