public void ShouldChainCorrectly() { // Arrange var logStrategy = new Mock <ILogStrategy>(); logStrategy.Setup(x => x.WriteMessage(It.IsAny <string>())).Verifiable(); var debugLogger = new RawLogger().Init(LogLevel.Debug, logStrategy.Object); var infoLogger = new RawLogger().Init(LogLevel.Info, logStrategy.Object); var fatalLogger = new RawLogger().Init(LogLevel.Fatal, logStrategy.Object); debugLogger.SetNextLogger(infoLogger); infoLogger.SetNextLogger(fatalLogger); // Act debugLogger.LogMessage(LogLevel.Debug, "debug"); debugLogger.LogMessage(LogLevel.Info, "info"); debugLogger.LogMessage(LogLevel.Fatal, "fatal"); // Assert logStrategy.Verify(x => x.WriteMessage(It.IsAny <string>()), Times.Exactly(3)); logStrategy.Verify(x => x.WriteMessage(It.Is <string>(s => s.Contains($"{LogLevel.Debug}"))), Times.Once); logStrategy.Verify(x => x.WriteMessage(It.Is <string>(s => s.Contains($"{LogLevel.Info}"))), Times.Once); logStrategy.Verify(x => x.WriteMessage(It.Is <string>(s => s.Contains($"{LogLevel.Fatal}"))), Times.Once); }
/// <summary> /// All static classes and singletons meant for global /// usage are activated here. Some areas depend on these classes having their /// data loaded before the program starts (e.g., OdometerTracker), so it /// is very important that they are called here. All static classes should at /// the bare minimum implement an empty Activate() method to ensure their /// constructors are called /// </summary> private void ActivateStaticClasses() { EventBridge.Initialize(); DiagnosticsParser.Initialize(); CanMessageHandler.Initialize(); ConfigManager.LoadConfiguration(); DiagnosticLogger.Initialize(); RawLogger.Initialize(); PIDValueStager.Initialize(); _EngineDataParser = new EngineDataParser(); _Acceleration = new Acceleration(); _Trackers = new Trackers(); ChassisParameters.Initialize(); var engineFilePointer = new FileOpener(ConfigManager.Settings.Contents.engineFilePath); if (engineFilePointer.Exists()) { EngineSpec.SetEngineFile(engineFilePointer.absoluteFilepath); } else { MessageBox.Show("No engine files can be found. Horsepower and Torque settings will be inaccurate"); } SPNDefinitions.Activate(); //in VMSpc/Parsers/J1939/SPNDefinitions.cs - Defines every SPN object //Odometer.Activate(); //ParamData.Activate(); TireManager.Initialize(); CommunicationManager.Initialize(); DayNightManager.Initialize(); }
public void ShouldBeIgnored() { // Arrange var logStrategy = new Mock <ILogStrategy>(); logStrategy.Setup(x => x.WriteMessage(It.IsAny <string>())).Verifiable(); var infoLogger = new RawLogger().Init(LogLevel.Info, logStrategy.Object); // Act infoLogger.LogMessage(LogLevel.Fatal, "info"); // Assert logStrategy.Verify(x => x.WriteMessage(It.IsAny <string>()), Times.Never); }
/// <summary> /// Initialize the <see cref="AsyncDatabaseTraceListener" />. /// </summary> private void Initialize() { string configurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; XElement configuration = XDocument.Load(configurationFile).XPathSelectElement($"//system.diagnostics/sharedListeners/add[starts-with(@type, '{GetType().FullName}')]"); if (configuration == null) { RawLogger.LogError(ErrorCodes.Framework.ListenerInvalidConfiguration, InternalMessages.FrameworkListenerMissingConfiguration); return; } _maxTraceEventsByCall = GetAttributeValue(configuration, AttributeName.MaxTraceEventsByCall, Default.MaxTraceEventsByCall); _callFrequency = GetAttributeValue(configuration, AttributeName.CallFrequency, Default.CallFrequency); _maxQueueSize = GetAttributeValue(configuration, AttributeName.MaxQueueSize, Default.MaxQueueSize); var connectionStringAttribute = configuration.Attributes().FirstOrDefault(a => a.Name == AttributeName.ConnectionString); if (connectionStringAttribute == null) { // No connection string RawLogger.LogError(ErrorCodes.Framework.ListenerInvalidConfiguration, string.Format(CultureInfo.CurrentCulture, InternalMessages.FrameworkListenerMissingAttribute, AttributeName.ConnectionString)); return; } _connectionStringName = connectionStringAttribute.Value; // empty connection string if (string.IsNullOrWhiteSpace(_connectionStringName)) { RawLogger.LogError(ErrorCodes.Framework.ListenerInvalidConfiguration, string.Format(CultureInfo.CurrentCulture, InternalMessages.FrameworkListenerInvalidAttribute, AttributeName.ConnectionString)); return; } // select tha appropriate method to write events to store by checking if connection string is rest api uri // if not, it is assumed to be a sql connection string _writeEventsToStore = WriteEventsToDatabase; bool isRestApiMethodSelected = Uri.IsWellFormedUriString(_connectionStringName, UriKind.Absolute); if (isRestApiMethodSelected) { _restApiStoreUri = new Uri(_connectionStringName, UriKind.Absolute); _writeEventsToStore = WriteEventsToRestApi; } // start the timer if (_senderTimer == null) { _senderTimer = new Timer(TimerCallback, _senderTimer, 0, _callFrequency); } }
/// <summary> /// Sends up to MaxTraceEventbyPacket trace events to the writing delegate. /// </summary> /// <returns>True if there is still traces to emit, false otherwise.</returns> private bool SendTraces() { if (_writeEventsToStore == null || _tracesQueue.IsEmpty) { return(false); } int traceEventsCount = Math.Min(_maxTraceEventsByCall, _tracesQueue.Count); List <TraceEventData> eventsList = new List <TraceEventData>(); for (int i = 0; i < traceEventsCount; i++) { TraceEventData item; if (_tracesQueue.TryDequeue(out item)) { eventsList.Add(item); } else { break; } } if (eventsList.Count <= 0) { return(false); } try { _writeEventsToStore(eventsList); } catch (Exception exception) { // 1. Because the TraceListener is written to manage Exception we do not want to rethrow it, // once again to avoid infinite loop: but we log the error in the event-log to trace the problem. // 2. We also decrement a counter to avoid filling the event-log. if (--_remainingErrorsToLog > 0) { RawLogger.LogWarning(ErrorCodes.Framework.ListenerLoggingError, string.Format(CultureInfo.CurrentCulture, InternalMessages.FrameworkListenerLoggingError, exception)); } } return(true); }
private static int GetAttributeValue(XElement configuration, string attributeName, int defaultValue) { var attribute = configuration.Attributes().FirstOrDefault(a => a.Name == attributeName); if (attribute == null) { return(defaultValue); } int temp; if (int.TryParse(attribute.Value, out temp) && temp > 0) { return(temp); } RawLogger.LogWarning(ErrorCodes.Framework.ListenerInvalidConfiguration, string.Format(CultureInfo.CurrentCulture, InternalMessages.FrameworkListenerInvalidAttributeBackToDefault, attributeName, defaultValue)); return(defaultValue); }
/// <summary> /// Trace the specified data. /// </summary> /// <param name="eventCache">The specified cache object.</param> /// <param name="source">The name of the source</param> /// <param name="eventType">The specified System.Dagnostics trace event type.</param> /// <param name="id">The specified event id.</param> /// <param name="data">The custom data object that will hold our <see cref="TraceEventData" /> object.</param> public override void TraceData(TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, object data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null)) { return; } if (_tracesQueue.Count >= _maxQueueSize) { // No connection string if (--_remainingErrorsToLog > 0) { RawLogger.LogWarning(ErrorCodes.Framework.ListenerFlooded, InternalMessages.FrameworkListenerFlooded); } return; } _tracesQueue.Enqueue(data as TraceEventData); }