Esempio n. 1
0
        private static void ThreadFunc(object state)
        {
            int index = (int)state;

            ThreadContext.Set((index + ThreadCount).ToString(), index);
            Atomic.Inc(ref lock_);

            while (Atomic.Cas(ref lock_, ThreadCount, ThreadCount) != ThreadCount)
            {
                Soyo.Base.Thread.Sleep(1);
            }

            bool result = ThreadContext.Contains("1");

            Assert.IsFalse(result, "value should be false");;

            result = ThreadContext.Contains("2");
            Assert.IsFalse(result, "value should be false");;

            for (int i = 0; i < ThreadCount; i++)
            {
                object value = ThreadContext.Get((i + ThreadCount).ToString());
                if (i == index)
                {
                    Assert.AreEqual(value, index, "value should be index");
                }
                else
                {
                    Assert.IsNull(value, "value should be null");;
                }
                Atomic.Inc(ref checkCount_);
            }
        }
        public void TestEventsAreSentCorrectly()
        {
            var    ex   = new Exception("Hello");
            string msg1 = "Event1";
            string msg2 = "Event2";

            SystemEvents.DispatchDiagnosicEvent(msg1, LogLevel.Error);
            SystemEvents.DispatchDiagnosicEvent(msg2, LogLevel.Fatal, ex);
            var events = _genertorUnderTest.GetEvents().Cast <Diagnostic>().ToList();

            Assert.AreEqual(2, events.Count());

            var pid = Process.GetCurrentProcess().Id;
            var tid = Thread.CurrentThread.ManagedThreadId;

            var actualEvent = events.ElementAt(0);

            Assert.AreEqual(pid, actualEvent.Payload.First().ProcessId);
            Assert.AreEqual(tid, actualEvent.Payload.First().ThreadId);
            Assert.AreEqual(msg1, actualEvent.Payload.First().Message);
            Assert.AreEqual(LogLevel.Error.ToString(), actualEvent.Payload.First().Severity);
            Assert.AreEqual(ThreadContext.Get().ExecutionId, actualEvent.Payload.First().CorrelationId);

            actualEvent = events.ElementAt(1);
            Assert.AreEqual(pid, actualEvent.Payload.First().ProcessId);
            Assert.AreEqual(tid, actualEvent.Payload.First().ThreadId);
            Assert.AreEqual(ex.FormatExceptionMessage(msg2), actualEvent.Payload.First().Message);
            Assert.AreEqual(LogLevel.Fatal.ToString(), actualEvent.Payload.First().Severity);
            Assert.AreEqual(ThreadContext.Get().ExecutionId, actualEvent.Payload.First().CorrelationId);
        }
        /// <summary>
        /// Send the message asynchronously
        /// </summary>
        /// <param name="eventsToSend">The events to send in the message</param>
        /// <param name="messagePriority">Message priority</param>
        /// <returns>The awaitable task returned by the SDK</returns>
        private async Task SendMessage(IEnumerable <IEvent> eventsToSend, EventPriority messagePriority)
        {
            var          context = ThreadContext.Get();
            AgentMessage message = new AgentMessage(eventsToSend,
                                                    LocalConfiguration.General.AgentId,
                                                    LocalConfiguration.AgentVersion);

            try
            {
                await ExternalInterfaceFacade.Instance.ExternalClient.SendMessage(message,
                                                                                  new Dictionary <string, string>
                {
                    { "MessagePriority", messagePriority.ToString() }
                });

                ThreadContext.Set(context);
                SimpleLogger.Debug("Message sent: " + message.GetPrintableMessage());
                CounterType.SendSuccesfully.Get().Increment();
            }
            catch (Exception e)
            {
                ThreadContext.Set(context);
                SimpleLogger.Warning("Message failed to sent: " + message.GetPrintableMessage(), false, e);
                CounterType.SendFailed.Get().Increment();
            }
        }
Esempio n. 4
0
        private void CreateDiagnosticEvent(string message, LogLevel severity, Exception exception = null)
        {
            var payload = new DiagnosticPayload()
            {
                CorrelationId = ThreadContext.Get().ExecutionId,
                Severity      = severity.ToString(),
                Message       = exception == null ? message : exception.FormatExceptionMessage(message),
                ProcessId     = Process.GetCurrentProcess().Id,
                ThreadId      = Thread.CurrentThread.ManagedThreadId
            };

            _internalBuffer.Enqueue(new Diagnostic(Priority, payload));
        }
        /// <summary>
        /// Logs a message according to the LogLevel,
        /// Also sends an operational event according to DiagnosticEventLevel
        /// </summary>
        /// <param name="message">The log line</param>
        /// <param name="level">The level at which to log this message</param>
        /// <param name="sendAsDiagnostic">whether or not go generate a diagnostic event due to this log</param>
        /// <param name="exception">The exception, if any</param>
        private static void Log(string message, LogLevel level, bool sendAsDiagnostic, Exception exception = null)
        {
            if (level == LogLevel.Off)
            {
                throw new ArgumentException(
                          "tried logging a message with severity [off], something went terribly wrong https://www.youtube.com/watch?v=t3otBjVZzT0");
            }

            if (LocalConfiguration.General.LogLevel < level)
            {
                return;
            }

            Guid correlationId = ThreadContext.Get().ExecutionId;

            string formattedMessage = exception == null ? message : exception.FormatExceptionMessage(message);
            string logLine          = $"{DateTime.Now} | CorrelationId: {correlationId} | {level.ToString()}: {formattedMessage}";

            Trace.WriteLine(logLine);

            if (LocalConfiguration.General.FileLogLevel >= level)
            {
                lock (LogFileLock)
                {
                    _logFileStreamWriter.WriteLine(logLine);
                    _logFileStreamWriter.Flush();
                }
            }

            if (AgentConfiguration.IsInitialized())
            {
                if (LocalConfiguration.General.DiagnosticVerbosityLevel == DiagnosticVerbosity.All ||
                    (LocalConfiguration.General.DiagnosticVerbosityLevel == DiagnosticVerbosity.Some && sendAsDiagnostic))
                {
                    SendDiagnosticEvent(formattedMessage, level, correlationId);
                }
            }
        }
Esempio n. 6
0
        private static void CheckContext()
        {
            var t = new ThreadContext();
            var result = t.Get<string>("c");
            if (!string.IsNullOrEmpty(result))
            {
                throw new InvalidDataException();
            }

            t.Set("c", "a");
            if (t.Get<string>("c") != "a")
            {
                throw new InvalidDataException();
            }
        }
Esempio n. 7
0
        public void ThreadContext_Sharing_TEST()
        {
            var tc = new ThreadContext();
            var k = "a";

            var threadTimes = new Dictionary<int, DateTime>();

            var action = new Action(
                () =>
                {
                    var tk = Thread.CurrentThread.ManagedThreadId;
                    DateTime? now = DateTime.Now;

                    Assert.IsFalse(tc.Get<DateTime?>(k).HasValue);

                    if (!tc.Get<DateTime?>(k).HasValue)
                    {
                        tc.Set(k, now);

                        if (!threadTimes.ContainsKey(tk))
                        {
                            threadTimes[tk] = now.Value;
                        }
                    }

                    Assert.AreEqual(now.Value.Ticks, tc.Get<DateTime?>(k).Value.Ticks);
                });

            var tasks = new List<Task>();

            for (int i = 0; i < 100000; i++)
            {
                tasks.Add(Task.Factory.StartNew(action));
            }

            Task.WaitAll(tasks.ToArray());

            Assert.IsTrue(true);
        }
Esempio n. 8
0
 public void ThreadContext_Get_Set_TEST()
 {
     var tc = new ThreadContext();
     tc.Set("a", 1);
     Assert.AreEqual(1, tc.Get<int>("a"));
 }
Esempio n. 9
0
 public void ThreadContext_Get_Set_Guid_TEST()
 {
     var tc = new ThreadContext();
     var guid = Guid.NewGuid();
     tc.Set("b", guid);
     Assert.AreEqual(guid, tc.Get<Guid>("b"));
 }
Esempio n. 10
0
        public void TestThreadContext()
        {
            ThreadContext.Set("1", 1);

            var set = ThreadContext.PropertySet;

            set["2"] = 2;

            object value = ThreadContext.Get("1");

            Assert.AreEqual(value, 1, "value should be 1");

            value = set["2"];
            Assert.AreEqual(value, 2, "value should be 2");

            bool result = ThreadContext.Contains("1");

            Assert.IsTrue(result, "resutl should be true");

            result = ThreadContext.Contains("2");
            Assert.IsTrue(result, "resutl should be true");

            result = ThreadContext.Contains("3");
            Assert.IsFalse(result, "resutl should be false");

            value = ThreadContext.Get("3");
            Assert.IsNull(value, "value should be null");

            ThreadContext.Remove("1");

            result = ThreadContext.Contains("1");
            Assert.IsFalse(result, "resutl should be false");

            ThreadContext.Clear();

            result = ThreadContext.Contains("2");
            Assert.IsFalse(result, "resutl should be false");

            ThreadContext.Set("1", 1);
            ThreadContext.Set("2", 2);
            List <System.Threading.Thread> threadList = new List <System.Threading.Thread>();

            for (int i = 0; i < ThreadCount; i++)
            {
                var thread = new System.Threading.Thread(ThreadFunc);
                Assert.IsNotNull(thread, "value should not be null");
                threadList.Add(thread);
                thread.Start(i);
            }

            for (int i = 0; i < threadList.Count; i++)
            {
                threadList[i].Join();
            }

            for (int i = 0; i < ThreadCount; i++)
            {
                value = ThreadContext.Get((i + ThreadCount).ToString());
                Assert.IsNull(value, "value should be null");;
            }

            Assert.AreEqual(checkCount_, ThreadCount * ThreadCount, "value should be ThreadCount * ThreadCount");
        }