示例#1
0
		/// <summary>
		/// Executes a docking station diagnostic operation.
		/// </summary>
		/// <returns>Docking station event</returns>
		public DockingStationEvent Execute()
		{
            // Initialize resource manager's culture to be same as current configuration culture.
            DiagnosticResources.Culture = Configuration.DockingStation.Language.Culture;
			
            // Make the return event and return diagnostic and wire them together.
            DiagnosticEvent dsEvent = new DiagnosticEvent( this );
            dsEvent.DockingStation = Controller.GetDockingStation(); // Retrieve IDS's complete information.

            // Make the builder for the details.
            DetailsBuilder details = new DetailsBuilder();

            details.AddDockingStation( dsEvent.DockingStation );

            // SGF  23-May-2011  INS-1741
            ReportDiagnosticDate(details);

            GeneralDiagnostic generalDiagnostic = new GeneralDiagnostic( Configuration.DockingStation.SerialNumber, DateTime.UtcNow );

            ExecuteDiagnostics( dsEvent, details );

			// Retrieve the details.
			dsEvent.Details = details.ToString();

			// Write the details to a log file.
            FlashCard.WriteTextFile( LAST_RUN_DETAILS_FILE_NAME, dsEvent.Details );

            dsEvent.Diagnostics.Add( generalDiagnostic );
            generalDiagnostic.Items = _gdpList.ToArray();

            return dsEvent;  // Return the event
		}
        public override bool Evaluate(DiagnosticEvent diagnosticEvent, ILoggerName loggerName)
        {
            bool meetsCriteria = true;

            if (!Evaluator.Value.MatchesPattern(diagnosticEvent.LoggerName))
            {
                meetsCriteria = false;
            }
            else
            {
                foreach (var name in loggerName.NamePartHierarchy)
                {
                    if (!Evaluator.Value.MatchesPattern(name))
                    {
                        meetsCriteria = false;
                        break;
                    }
                }
            }

            if (Mode == FilterMode.Include)
                return meetsCriteria;
            else
                return !meetsCriteria;
        }
示例#3
0
        /// <summary>
        /// </summary>
        /// <remarks>
        /// 23-Feb-2011, Originally based on following dev jiras...
        /// http://svrdevjira/browse/DSHW-120
        /// http://svrdevjira/browse/INS-3124
        /// </remarks>
        /// <param name="dsEvent"></param>
        /// <param name="details"></param>
        private void ExecuteDiagnostics( DiagnosticEvent dsEvent, DetailsBuilder details )
        {
            Log.Debug("ExecuteDiagnostics: Self-diagnostics starting.");
            InitializeEnvironment(details);

            try
            {
//#if !DEBUG
                TestSystemCurrent( details );
                TestCoreVoltage( details );
                TestEthernet( details );
                TestVacuumSensor( details );
                TestFlowSensor( details );
                TestForLeak( details );
                TestPump( details );
				//TestSolenoids( details );
                for ( int portNum = 1; portNum <= Configuration.DockingStation.NumGasPorts; portNum++ )
                    TestFlow( details, portNum );
//#endif
            }
            catch ( Exception e )
            {
                Log.Error( e );
                throw;
            }
            finally
            {
                RestoreEnvironment( details );
            }

            Log.Debug("ExecuteDiagnostics: Self-diagnostics complete.");
        }
        public static DiagnosticEvent Decode(byte[] buffer)
        {
            var result = new DiagnosticEvent();

            int offset    = 0;
            var blocksize = (UInt32)Unmarshall(buffer, ref offset, TypeCode.UInt32);

            if (buffer.Length != blocksize)
            {
                throw new Exception("invalid event record");
            }
            result.EventTag = (UInt32)Unmarshall(buffer, ref offset, TypeCode.UInt32);
            var ticks = (Int64)Unmarshall(buffer, ref offset, TypeCode.Int64);

            result.Timestamp = new DateTime(ticks);
            result.Category  = (UInt32)Unmarshall(buffer, ref offset, TypeCode.UInt32);
            result.Severity  = (Severity)Unmarshall(buffer, ref offset, TypeCode.Byte);
            var tcArray = (TypeCode[])Unmarshall(buffer, ref offset, TypeCode.Empty);

            result.Args = new object[tcArray.Length];
            for (int i = 0; i < tcArray.Length; ++i)
            {
                result.Args[i] = Unmarshall(buffer, ref offset, tcArray[i]);
            }
            return(result);
        }
示例#5
0
 public void Consume(DiagnosticEvent @event)
 {
     lock (_syncRoot)
     {
         _consumedEvents.Add(@event);
     }
 }
        public async Task ExecuteBatchAsync_WritesToTableStorage()
        {
            IEnvironment testEnvironment = new TestEnvironment();

            testEnvironment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "0");

            DiagnosticEventTableStorageRepository repository =
                new DiagnosticEventTableStorageRepository(_configuration, _hostIdProvider, testEnvironment, _logger);

            var table = repository.GetDiagnosticEventsTable();
            await TableStorageHelpers.CreateIfNotExistsAsync(table, 2);

            await EmptyTableAsync(table);

            var dateTime        = DateTime.UtcNow;
            var diagnosticEvent = new DiagnosticEvent("hostId", dateTime);
            var events          = new ConcurrentDictionary <string, DiagnosticEvent>();

            events.TryAdd("EC123", diagnosticEvent);
            await repository.ExecuteBatchAsync(events, table);

            var results = ExecuteQuery(table, new TableQuery());

            Assert.Equal(results.Count(), 1);
        }
 public bool ProcessEvent(DiagnosticEvent diagnosticEvent, int sessionId)
 {
     var session = GetPlayerSession(sessionId, true);
     bool entryCreated = false;
     session.AddSample(diagnosticEvent, RecordEvent(diagnosticEvent), ref entryCreated);
     return entryCreated;
 }
        public void EventDataPlayerSession_HandleOperationDestroy_DoesNotDestroyOnNonzeroRefcount()
        {
            EventDataPlayerSession edps = new EventDataPlayerSession();

            DiagnosticEvent creationEvt = CreateNewGenericEvent(ResourceManager.DiagnosticEventType.AsyncOperationCreate, 0, 1, 1000);
            DiagnosticEvent refcountEvt = CreateNewGenericEvent(ResourceManager.DiagnosticEventType.AsyncOperationReferenceCount, 0, 1, 1000);
            DiagnosticEvent deletionEvt = CreateNewGenericEvent(ResourceManager.DiagnosticEventType.AsyncOperationDestroy, 1, 1, 1000);

            bool entryCreated = false;

            edps.AddSample(creationEvt, false, ref entryCreated);
            Assert.IsTrue(entryCreated, "creationEvt: Either a new entry was supposed to be created, but was not, or the value of entryCreated was not properly updated.");

            edps.AddSample(refcountEvt, false, ref entryCreated);
            Assert.IsFalse(entryCreated, "refcountEvt: Either a new entry was created when it shouldn't have been, or the value of entryCreated was not properly updated.");

            edps.AddSample(deletionEvt, false, ref entryCreated);
            Assert.IsFalse(entryCreated, "deletionEvt: Either a new entry was created when it shouldn't have been, or the value of entryCreated was not properly updated.");

            Assert.AreEqual(1, edps.m_Queue.Count, "Deletion event should've been added to the removal queue.");

            edps.HandleOperationDestroy(deletionEvt);

            Assert.IsTrue(edps.m_DataSets.ContainsKey(creationEvt.ObjectId), "Dataset should not have been removed because it's refcount is greater than 0. ");
        }
        public async Task ExecuteBatchAsync_LogsError()
        {
            IEnvironment testEnvironment = new TestEnvironment();

            testEnvironment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "0");

            DiagnosticEventTableStorageRepository repository =
                new DiagnosticEventTableStorageRepository(_configuration, _hostIdProvider, testEnvironment, _logger);

            var tableClient = repository.TableClient;
            var table       = tableClient.GetTableReference("aa");

            var dateTime        = DateTime.UtcNow;
            var diagnosticEvent = new DiagnosticEvent("hostId", dateTime);

            var events = new ConcurrentDictionary <string, DiagnosticEvent>();

            events.TryAdd("EC123", diagnosticEvent);
            await repository.ExecuteBatchAsync(events, table);

            ExecuteQuery(table, new TableQuery());
            string message = _loggerProvider.GetAllLogMessages()[0].FormattedMessage;

            Assert.True(message.StartsWith("Unable to write diagnostic events to table storage"));
        }
        public void EventDataPlayerSession_HandleOperationDestroy_DestroyedEventHasParentCase()
        {
            EventDataPlayerSession edps = new EventDataPlayerSession();

            DiagnosticEvent dependencyEvt = CreateNewGenericEvent(ResourceManager.DiagnosticEventType.AsyncOperationReferenceCount, 0, 0, 1001);
            DiagnosticEvent creationEvt   = CreateNewGenericEvent(ResourceManager.DiagnosticEventType.AsyncOperationCreate, 0, 1, 1000, new int[] { dependencyEvt.ObjectId });
            DiagnosticEvent deletionEvt   = CreateNewGenericEvent(ResourceManager.DiagnosticEventType.AsyncOperationDestroy, 1, 1, 1001);

            bool entryCreated = false;

            edps.AddSample(dependencyEvt, false, ref entryCreated);
            Assert.IsTrue(entryCreated, "Either a new entry was supposed to be created, but was not, or the value of entryCreated was not properly updated.");

            edps.AddSample(creationEvt, false, ref entryCreated);
            Assert.IsTrue(entryCreated, "Either a new entry was supposed to be created, but was not, or the value of entryCreated was not properly updated.");

            edps.AddSample(deletionEvt, false, ref entryCreated);
            Assert.IsFalse(entryCreated, "Either a new entry was created when it shouldn't have been, or the value of entryCreated was not properly updated.");
            Assert.AreEqual(1, edps.m_RootStreamEntry.Children.Count(), "DependencyEvt's id should have been removed from RootStreamEntry's children because it is a dependency.");

            Assert.AreEqual(1, edps.m_Queue.Count, "Deletion event should have been added to the removal queue.");

            edps.HandleOperationDestroy(deletionEvt);

            Assert.IsFalse(edps.m_DataSets.ContainsKey(deletionEvt.ObjectId), "DataSet was not properly removed after dependency was cleared. ");

            EventDataSet creationEvtEds = null;

            Assert.IsTrue(edps.m_DataSets.TryGetValue(creationEvt.ObjectId, out creationEvtEds), "Parent event was removed from m_DataSets incorrectly.");
            Assert.IsNull(creationEvtEds.m_Children, "dependencyEvt's dataset should have been removed from the children of creationEvt's dataset. ");

            Assert.AreEqual(1, edps.m_Queue.Count, "No further deletion events should have been added to the deletion queue.");
        }
        public void EventDataPlayerSession_AddSample_SimpleInstantiationCase()
        {
            EventDataPlayerSession edps = new EventDataPlayerSession();

            DiagnosticEvent evt1 = CreateNewInstantiationEvent(0, 1);
            DiagnosticEvent evt2 = CreateNewInstantiationEvent(0, 1);
            DiagnosticEvent evt3 = CreateNewInstantiationEvent(1, 1);
            DiagnosticEvent evt4 = CreateNewInstantiationEvent(2, 0);

            bool entryCreated = false;

            edps.AddSample(evt1, false, ref entryCreated);
            Assert.IsFalse(entryCreated, "evt1: Either a new entry was created when it shouldn't have been, or the value of entryCreated was not properly updated.");

            edps.AddSample(evt2, false, ref entryCreated);
            Assert.IsFalse(entryCreated, "evt2: Either a new entry was created when it shouldn't have been, or the value of entryCreated was not properly updated.");

            edps.AddSample(evt3, false, ref entryCreated);
            Assert.IsFalse(entryCreated, "evt3: Either a new entry was created when it shouldn't have been, or the value of entryCreated was not properly updated.");

            Assert.AreEqual(2, edps.m_InstantitationCountDataSet.GetStreamValue(0, 0), "Stream value for frame 0 not properly set to 2.");
            Assert.AreEqual(2, edps.m_InstantitationCountDataSet.GetStreamValue(0, 1), "Stream value for frame 1 was updated prematurely - stream values for instantiation counts should not be updated until it is certain that all events for a given frame have been collected. ");

            edps.AddSample(evt4, false, ref entryCreated);
            Assert.IsFalse(entryCreated, "evt3: Either a new entry was created when it shouldn't have been, or the value of entryCreated was not properly updated.");

            Assert.AreEqual(1, edps.m_InstantitationCountDataSet.GetStreamValue(0, 1), "Stream value for frame 1 was not updated properly, should be updated once the sample is added for the following frame.");
        }
        internal void HandleEventDataSetCreation(DiagnosticEvent evt)
        {
            var ds = new EventDataSet(evt);

            m_DataSets.Add(evt.ObjectId, ds);
            if (evt.Dependencies != null)
            {
                foreach (var d in evt.Dependencies)
                {
                    EventDataSet depDS;
                    if (m_DataSets.TryGetValue(d, out depDS))
                    {
                        ds.AddChild(depDS);
                        HashSet <int> depParents = null;
                        if (!m_objectToParents.TryGetValue(d, out depParents))
                        {
                            RootStreamEntry.RemoveChild(d);
                            m_objectToParents.Add(d, depParents = new HashSet <int>());
                        }
                        depParents.Add(evt.ObjectId);
                    }
                }
            }

            if (!m_objectToParents.ContainsKey(evt.ObjectId))
            {
                RootStreamEntry.AddChild(ds);
            }
        }
示例#13
0
        void OnEventProcessed(DiagnosticEvent diagnosticEvent, bool entryCreated)
        {
            if (!CanHandleEvent(diagnosticEvent.Graph))
            {
                return;
            }

            bool moveInspectFrame = m_LatestFrame < 0 || m_InspectFrame == m_LatestFrame;

            m_LatestFrame = diagnosticEvent.Frame;
            if (entryCreated)
            {
                if (m_GraphList != null)
                {
                    m_GraphList.Reload();
                }
            }

            if (moveInspectFrame)
            {
                SetInspectFrame(m_LatestFrame);
            }

            if (diagnosticEvent.Frame != m_lastRepaintedFrame)
            {
                Repaint();
                m_lastRepaintedFrame = diagnosticEvent.Frame;
            }
        }
示例#14
0
        public void DataSinceFromLastDiagnostic()
        {
            IDiagnosticStore _serverDiagnosticStore = CreateDiagnosticStore(null);
            DiagnosticEvent  periodicEvent          = _serverDiagnosticStore.CreateEventAndReset();

            Assert.Equal(periodicEvent.JsonValue.Get("creationDate").AsLong,
                         UnixMillisecondTime.FromDateTime(_serverDiagnosticStore.DataSince).Value);
        }
示例#15
0
 bool RecordEvent(DiagnosticEvent e)
 {
     if (m_OnRecordEvent != null)
     {
         return(m_OnRecordEvent(e));
     }
     return(false);
 }
 protected void NullEventsDoNotSatisfySpec()
 {
     Event = null;
     GivenMinLevel(DiagnosticEventLevel.Trace);
     GivenMaxLevel(DiagnosticEventLevel.Error);
     WhenEvaluating();
     AssertSpecificationNotSatisified();
 }
        public void Consume(DiagnosticEvent @event)
        {
            var logLevel = GetLogLevel(@event);
            var eventId  = GetEventId(@event);
            var state    = GetState(@event);

            _logger.Log(logLevel, eventId, state, @event.Exception, Format);
        }
        public void DataSinceFromLastDiagnostic()
        {
            IDiagnosticStore _serverDiagnosticStore = CreateDiagnosticStore();
            DiagnosticEvent  periodicEvent          = _serverDiagnosticStore.CreateEventAndReset();

            Assert.Equal(periodicEvent.JsonValue.Get("creationDate").AsLong,
                         Util.GetUnixTimestampMillis(_serverDiagnosticStore.DataSince));
        }
示例#19
0
 private bool IsHandlerActivationError(DiagnosticEvent e)
 {
     Assert.NotNull(e);
     Assert.Equal(DiagnosticEventType.HandlerActivationError, e.Type);
     Assert.Equal(Exception, e.Exception);
     Assert.StartsWith("Error activating instance of message handler ", e.Detail);
     return(true);
 }
示例#20
0
        public void CanIncrementDeduplicateUsers()
        {
            IDiagnosticStore _serverDiagnosticStore = CreateDiagnosticStore(null);

            _serverDiagnosticStore.IncrementDeduplicatedUsers();
            DiagnosticEvent periodicEvent = _serverDiagnosticStore.CreateEventAndReset();

            Assert.Equal(1, periodicEvent.JsonValue.Get("deduplicatedUsers").AsInt);
        }
        public void CanIncrementDroppedEvents()
        {
            IDiagnosticStore _serverDiagnosticStore = CreateDiagnosticStore();

            _serverDiagnosticStore.IncrementDroppedEvents();
            DiagnosticEvent periodicEvent = _serverDiagnosticStore.CreateEventAndReset();

            Assert.Equal(1, periodicEvent.JsonValue.Get("droppedEvents").AsInt);
        }
        public void CanRecordEventsInBatch()
        {
            IDiagnosticStore _serverDiagnosticStore = CreateDiagnosticStore();

            _serverDiagnosticStore.RecordEventsInBatch(4);
            DiagnosticEvent periodicEvent = _serverDiagnosticStore.CreateEventAndReset();

            Assert.Equal(4, periodicEvent.JsonValue.Get("eventsInLastBatch").AsInt);
        }
        internal ServerDiagnosticStore(Configuration config)
        {
            DateTime currentTime = DateTime.Now;

            Config       = config;
            DataSince    = currentTime.ToBinary();
            DiagnosticId = new DiagnosticId(config.SdkKey, Guid.NewGuid());
            InitEvent    = BuildInitEvent(currentTime);
        }
示例#24
0
        public Task ConsumeAsync(DiagnosticEvent @event, CancellationToken cancellationToken = default(CancellationToken))
        {
            lock (_syncRoot)
            {
                _consumedEvents.Add(@event);
            }

            return(Task.FromResult(0));
        }
        /// <inheritdoc />
        public bool IsSatisfiedBy(DiagnosticEvent @event)
        {
            if (@event == null)
            {
                return(false);
            }
            var level = @event.Type.Level;

            return(level >= _minLevel && level <= _maxLevel);
        }
        public void ProcessAuditEvent(DiagnosticEvent de)
        {
            //if (de == null)
            //    return;

            //// TODO: read config specific to Audit
            //var config_ref = Volatile.Read(ref TraceConfigCache);

            //ProcessDiagnosticEvent(de, config_ref);
        }
        public void PeriodicEventUsesIdFromInit()
        {
            IDiagnosticStore _serverDiagnosticStore = CreateDiagnosticStore();
            DiagnosticEvent? initEvent = _serverDiagnosticStore.InitEvent;

            Assert.True(initEvent.HasValue);
            DiagnosticEvent periodicEvent = _serverDiagnosticStore.CreateEventAndReset();

            Assert.Equal(initEvent.Value.JsonValue.Get("id"), periodicEvent.JsonValue.Get("id"));
        }
 internal void HandleInstantiationEvent(DiagnosticEvent evt)
 {
     if (m_InstantitationCountDataSet == null)
     {
         m_InstantitationCountDataSet = new EventDataSet(1, "InstantiationCount", "Instantiation Counts", EventDataSet.k_InstanceCountSortOrder);
         RootStreamEntry.AddChild(m_InstantitationCountDataSet);
     }
     m_LastInstantiationFrame = evt.Frame;
     m_LastFrameInstantiationCount++;
 }
示例#29
0
        private void ConnectionStateChanged()
        {
            var connectionEvent = new DiagnosticEvent
            {
                Message   = ConnectionStatus,
                TimeStamp = DateTime.UtcNow
            };

            _diagnosticEventsSubject.OnNext(connectionEvent);
        }
 public void Consume(DiagnosticEvent @event)
 {
     lock (_syncRoot)
     {
         _emittedEvents.AddFirst(@event);
         while (_emittedEvents.Count > 1000)
         {
             _emittedEvents.RemoveLast();
         }
     }
 }
示例#31
0
        public void OnEvent(DiagnosticEvent diagnosticEvent, int session)
        {
            if (m_EventData == null)
            {
                m_EventData = new EventDataPlayerSessionCollection(OnRecordEvent);
            }

            var entryCreated = m_EventData.ProcessEvent(diagnosticEvent, session);

            OnEventProcessed(diagnosticEvent, entryCreated);
        }
        protected override bool OnDrawColumnCell(Rect cellRect, DiagnosticEvent evt, int column)
        {
            switch (column)
            {
            case 0: EditorGUI.LabelField(cellRect, ((ResourceManager.DiagnosticEventType)evt.Stream).ToString()); break;

            case 1: EditorGUI.LabelField(cellRect, evt.DisplayName); break;
            }

            return(true);
        }
            public static void TraceInformation(DiagnosticEvent de)
            {
                if (!InternalLoggerSwitch.Enabled)
                    return;

                try
                {
                    System.Diagnostics.Trace.WriteLine(de.DumpToString());
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex.ToString());
                }
            }
        public void Format__CorrectlyFormatsAllPlaceholders()
        {
            var pattern = "ABC{P.1}{P.2} DEF {P.3}";

            var formatter = new PatternFormatter();
            formatter.Pattern = pattern;

            var de = new DiagnosticEvent();
            de.Properties.TryAddProperty("P.1", () => 1);
            de.Properties.TryAddProperty("P.2", () => 2);
            de.Properties.TryAddProperty("P.3", () => 3);

            var resut = formatter.Format(de, new TypeDescriptorCollection());

            Assert.AreEqual("ABC12 DEF 3", resut);
        }
        public override bool Evaluate(DiagnosticEvent diagnosticEvent, ILoggerName loggerName)
        {
            bool meetsCriteria = false;

            if (Severity != null)
            {
                meetsCriteria = diagnosticEvent.Severity == Severity;
            }
            else if (From != null && To != null)
            {
                meetsCriteria = diagnosticEvent.Severity >= From && diagnosticEvent.Severity <= To;
            }
            else if (From != null)
            {
                meetsCriteria = diagnosticEvent.Severity >= From;
            }
            else if (To != null)
            {
                meetsCriteria = diagnosticEvent.Severity <= To;
            }
            else
            {
                if (ExclusiveFrom != null && ExclusiveTo != null)
                {
                    meetsCriteria = diagnosticEvent.Severity >= ExclusiveFrom && diagnosticEvent.Severity <= ExclusiveTo;
                }
                else if (ExclusiveFrom != null)
                {
                    meetsCriteria = diagnosticEvent.Severity > ExclusiveFrom;
                }
                else if (ExclusiveFrom != null)
                {
                    meetsCriteria = diagnosticEvent.Severity < ExclusiveTo;
                }
            }

            if (Mode == FilterMode.Include)
                return meetsCriteria;
            else
                return !meetsCriteria;
        }
        public override bool Evaluate(DiagnosticEvent diagnosticEvent, ILoggerName loggerName)
        {
            bool meetsCriteria = false;

            DiagnosticEventProperty property = new DiagnosticEventProperty();

            if (!diagnosticEvent.Properties.TryGetProperty(Property, out property))
            {
                Diag.Log.Warning(() =>
                    "Diagnostic Property '{0}' not found on Diagnostic Event."
                    .FormatWith(Property));

                meetsCriteria = false;
            }
            else
            {
                meetsCriteria = Evaluator.Value.MatchesPattern(property.Value.ToString());
            }

            if (Mode == FilterMode.Include)
                return meetsCriteria;
            else
                return !meetsCriteria;
        }
        public void ProcessLogEvent(DiagnosticEvent de)
        {
            if (de == null)
                return;

            ProcessDiagnosticEvent(de);
        }
示例#38
0
 public override bool Evaluate(DiagnosticEvent diagnosticEvent, ILoggerName loggerName)
 {
     return true;
 }
        public bool MeetsFiltersCriteria(DiagnosticEvent diagnosticEvent, ILoggerName loggerName, DiagnosticsConfiguration config)
        {
            //# check this loger's filters
            for (int i = 0; i < config.GlobalFilters.Count; i++)
            {
                var filter = config.GlobalFilters[i];

                bool shouldLog = filter.Evaluate(diagnosticEvent, loggerName);

                if (!shouldLog)
                    return false;
            }

            //# check parent loger's filter
            if (Parent != null)
                return Parent.MeetsFiltersCriteria(diagnosticEvent, loggerName, config);

            return true;
        }
        public void Configure(DiagnosticsConfiguration config)
        {
            config.LogConfigCache = new ConfigurationCache();

            config.SinkDefinitions.RefreshCache();

            foreach (var sink in config.SinkDefinitions)
                sink.Initialize();

            config.Sinks.RefreshCache();

            //# get log levels enabled states
            var de = new DiagnosticEvent();
            de.EvaluateAndPinAllDataIfNeeded();

            de.Severity = SeverityLevels.Critical;
            config.LogConfigCache.ShouldProcessCriticals = MeetsFiltersCriteria(de, Name, config);

            de.Severity = SeverityLevels.Error;
            config.LogConfigCache.ShouldProcessErrors = MeetsFiltersCriteria(de, Name, config);

            de.Severity = SeverityLevels.Warning;
            config.LogConfigCache.ShouldProcessWarnings = MeetsFiltersCriteria(de, Name, config);
            
            de.Severity = SeverityLevels.Information;
            config.LogConfigCache.ShouldProcessInformation = MeetsFiltersCriteria(de, Name, config);

            de.Severity = SeverityLevels.Verbose;
            config.LogConfigCache.ShouldProcessVerbose = MeetsFiltersCriteria(de, Name, config);

            //# get raw messages enabled states
            de.Severity = SeverityLevels.Maximum;
            de.HasRawMessage = true;
            config.LogConfigCache.ShouldProcessRawMessages = MeetsFiltersCriteria(de, Name, config);

            //# replace current config with new config
            //NOTE: we are setting some values on newCache, make sure that there's a memory barrier in place
            Thread.MemoryBarrier();
            Config = config;
        }
        public virtual void ProcessDiagnosticEvent(DiagnosticEvent de)
        {
            // NOTE:    this method is performance critical and should be optimized for quickest execution
            //          event at cost of readability

            try
            {
                // make a copy of reference to current configuration
                // to make sure that any changes (which would replace Config)
                // will not be applied to this method before it exits
                var config_ref = Config;

                if (config_ref.GlobalSettings.IncludeCallerInfo || config_ref.GlobalSettings.UseCallerNameAsLoggerName)
                {
                    de.IncludeCallerInformation(
                        config_ref.GlobalSettings.UseCallerNameAsLoggerName,
                        config_ref.GlobalSettings.IncludeCallerInfo);
                }

                // do not override logger name if it has already been set (custom name might have been used)
                if(de.LoggerName == null)
                    de.LoggerName = Name.ToString();

                // todo: Update DiagnosticEventPropertyCollection so that we don't have to use .ToList() here
                de.Properties.AddOrUpdateRange(GlobalProperties.ToList());

                //# EVALUATE AND PIN DIAGNOSTIC EVENT DATA
                de.EvaluateAndPinAllDataIfNeeded();

                //# FILTER
                if (config_ref.GlobalFilters.Count > 0 && !MeetsFiltersCriteria(de, Name, config_ref))
                    return;
                
                //# GET SINKS
                
                var mustWaitForWriteSinks = (ReadOnlyCollection<ISink>)null;
                var requestedContextData = (ReadOnlyCollection<DataRequest>)null;
                var isAdditionalContextdataRequested = false;

                mustWaitForWriteSinks = config_ref.Sinks.MustWaitForWriteSinks;
                requestedContextData = config_ref.Sinks.RequestedContextData;
                isAdditionalContextdataRequested = config_ref.Sinks.IsAdditionalContextDataRequested;

                //# INCLUDE DATA REQUESTED BY SINKS

                var requestedData = config_ref.GlobalContextDataCollectors.Collect(requestedContextData);
                de.Properties.AddOrUpdateRange(requestedData);

                //# GET ADDITIONAL CONTEXT INFORMATION

                if (isAdditionalContextdataRequested)
                {
                    var additionalContextdataCollectors = config_ref.AdditionalContextDataCollectors;

                    for (int i = 0; i < additionalContextdataCollectors.Count; i++)
                    {
                        var collector = additionalContextdataCollectors[i];

                        // if collector has no filter then it should be used.
                        if (collector.Filter == null)
                        {
                            de.AdditionalContextData = new DiagnosticEventPropertyCollection("AdditionalContextData", collector.CollectData());
                            de.PinAdditionalContextData();
                            break;
                        }

                        if (collector.Filter.Evaluate(de, this.Name))
                        {
                            de.AdditionalContextData = new DiagnosticEventPropertyCollection("AdditionalContextData", collector.CollectData());
                            de.PinAdditionalContextData();
                            break;
                        }
                    }
                }

                //# WRITE TO SINKS

                if (mustWaitForWriteSinks.Count > 0)
                {
                    if (mustWaitForWriteSinks.Count == 1)
                    {
                        var sink = mustWaitForWriteSinks.Single();
                        
                        if(sink.Filter.Evaluate(de, Name))
                            sink.Write(de);
                    }
                    else
                    {
                        Parallel.ForEach(mustWaitForWriteSinks, (sink) =>
                            {
                                try
                                {
                                    if (sink.Filter.Evaluate(de, Name))
                                        sink.Write(de);
                                }
                                catch (Exception ex)
                                {
                                    Diagnostics.Value.Log.Error(ex, "Failed to log diagnostic event.");
                                }
                            });
                    }
                }
                
                // then write to all fire-and-forget sinks
                var fireAndForgetSinks = config_ref.SinkDefinitions.FireAndForgetRawMessageSinks;

                if(fireAndForgetSinks.Count > 0)
                    ParallelExtensions.ForEachNoWait(
                        fireAndForgetSinks, 
                        (sink) =>
                            {
                                if (sink.Filter.Evaluate(de, Name))
                                    sink.Write(de);
                            });
            }
            catch(Exception ex)
            {
                Diagnostics.Value.Log.Error(ex, "Failed to log diagnostic event.");
            }
        }
 public override bool Evaluate(DiagnosticEvent diagnosticEvent, ILoggerName loggerName)
 {
     return ActualFilter.Value.Evaluate(diagnosticEvent, loggerName);
 }
 void UpdateBundledEvent(DiagnosticEvent ev, int bundleSize)
 {
     ev.Properties.AddOrUpdateProperty("Event-Bundle", true);
     ev.Properties.AddOrUpdateProperty("Event-Bundle.Size", bundleSize);
 }