using System; using System.Diagnostics; using System.Collections.Generic; using log4net; using Newtonsoft.Json; using TradeIdeas.MiscSupport; using System.IO; namespace TradeIdeas.Logging { public static class TILogger { private static readonly ILog _log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static Dictionary _logItemMetrics; static TILogger() { log4net.Config.XmlConfigurator.Configure(); _logItemMetrics = new Dictionary(); } /// /// Log an Error Item to the configured logging provider /// /// Usually the function where the error occurred. Default will use StackFrame /// A Message /// Exception object /// Optional, The Name of the Broker Interface /// Optional object containg fields to log. public static void Error(string message, Exception exception, string location = "", string broker = "", object data = null) { try { _log.Error(GetLogHeader(location, broker, message, data), exception); } catch (Exception) { } } /// /// Log an Information Item to the configured logging provider /// /// Usually the function where the logging originated. Default will use StackFrame /// A Message /// Exception object /// Optional, The Name of the Broker Interface public static void Information(string message, string location = "", string broker = "", object data = null) { try { _log.Info(GetLogHeader(location, broker, message, data)); } catch (Exception) { } } /// /// Log a Warning Item to the configured logging provider /// /// Usually the function where the logging originated. Default will use StackFrame /// A Message /// Exception object /// Optional, The Name of the Broker Interface public static void Warning(string message, string location = "", string broker="", object data = null) { try { _log.Warn(GetLogHeader(location, broker, message, data)); } catch (Exception) { } } private static string GetLogHeader(string location, string broker, string message, object data = null) { if (string.IsNullOrEmpty(location)) { //Skip 2 frames to get back to the souce of log invocation StackFrame stackFrame = new StackFrame(2, true); location = $"{stackFrame.GetMethod().DeclaringType.FullName}::{stackFrame.GetMethod().Name}"; } var logItemKey = $"{TIUserSession.Id},{location},{broker},{message}"; if ( !_logItemMetrics.ContainsKey(logItemKey)) { _logItemMetrics.Add(logItemKey, new LogItemMetric()); } _logItemMetrics[logItemKey].Counter++; _logItemMetrics[logItemKey].Last = DateTime.Now; return JsonConvert.SerializeObject(new LogHeader() { connectionType = TIUserSession.ConnectionType, userName = TIUserSession.UserName, version = TIUserSession.ApplicationVersion, broker = broker, sessionId = TIUserSession.Id, location = location, message = message, data = data }); } } }