public void LogError(Exception exception)
 {
     try
     {
         if (IsLogError)
         {
             Dictionary <string, string> exceptionDictionary = new Dictionary <string, string>();
             exceptionDictionary.Add("PreciseTimeStamp", DateTime.Now.Ticks.ToString());
             exceptionDictionary.Add("Error Message", exception.Message);
             foreach (DictionaryEntry exceptionData in exception.Data)
             {
                 exceptionDictionary.Add(exceptionData.Key.ToString(), exceptionData.Value.ToString());
             }
             exceptionDictionary.Add("LogFileName", logFileName);
             TelemetryClient.Context.Operation.Id = CorrelationId.ToString();
             TelemetryClient.TrackException(exception, exceptionDictionary);
             TelemetryClient.Flush();
         }
     }
     catch (LogMangerException)
     {
         throw;
     }
     catch (Exception)
     {
         // Empty catch, as it is used by global execption handler to log error. If some
         // exception is thrown from this method it will result in endless loop.
     }
 }
Пример #2
0
        private void Log(
            string message,
            object data,
            Exception ex,
            string source,
            LogEventLevel level,
            Action <string, LogMessage> logger)
        {
            var logMessage = new LogMessage
            {
                Application   = _appName,
                Data          = data ?? RequestBody,
                Level         = level.ToString(),
                Message       = message,
                Method        = source,
                Timestamp     = DateTime.Now,
                RequestId     = RequestId.ToString(),
                CorrelationId = CorrelationId.ToString(),
                IpAddress     = IpAddress,
            };

            if (ex is not null)
            {
                logMessage.StackTrace = ex.StackTrace;
            }

            logger.Invoke("{@LogMessage}", logMessage);
        }
 public void TrackEvent(Enums.EnrollmentEvent eventName, Dictionary <string, string> properties)
 {
     try
     {
         if (IsLogTrack)
         {
             if (properties != null)
             {
                 properties.Add("LogFileName", logFileName);
                 properties.Add("PreciseTimeStamp", DateTime.Now.Ticks.ToString());
             }
             TelemetryClient.Context.Operation.Id = CorrelationId.ToString();
             if (properties != null)
             {
                 TelemetryClient.TrackEvent(eventName.ToString(), properties);
             }
             else
             {
                 TelemetryClient.TrackEvent(eventName.ToString());
             }
             TelemetryClient.Flush();
         }
     }
     catch (LogMangerException)
     {
         throw;
     }
     catch (Exception innerException)
     {
         throw new LogMangerException(nameof(ErrorCodeMessages.LoggerError106) + ": " + ErrorCodeMessages.LoggerError106, innerException);
     }
 }
        public async Task InvokeTest()
        {
            var mr = new MockRepository(MockBehavior.Strict);
            var next = mr.Create<OwinMiddleware>(MockBehavior.Strict, (OwinMiddleware)null);
            var ctx = mr.Create<IOwinContext>();
            var cidStore = mr.Create<ICorrelationIdStore>();
            var response = mr.Create<IOwinResponse>();
            var hDict = new HeaderDictionary(new Dictionary<string, string[]>());
            var correlationId = new CorrelationId();

            next.Setup(x => x.Invoke(ctx.Object)).Returns(Task.CompletedTask).Verifiable();
            ctx.SetupGet(x => x.Response).Returns(response.Object).Verifiable();
            response.SetupGet(x => x.Headers).Returns(hDict).Verifiable();
            cidStore.Setup(x => x.Read()).Returns(correlationId).Verifiable();

            Assert.AreEqual(0, hDict.Count);

            var midleware = new SetCorrelationIdHeaderMiddleware(next.Object, cidStore.Object);
            await midleware.Invoke(ctx.Object);

            Assert.AreEqual(1, hDict.Count);
            var actual = hDict["X-CORRELATIONID"];
            Assert.AreEqual(correlationId.ToString(), actual);
            mr.VerifyAll();
        }
Пример #5
0
        public void ToString_Should_Be_The_Same_As_Guid_ToString()
        {
            var baseBytes = ByteUtil.GenerateRandomByteArray(CorrelationId.GuidByteLength);

            var id1 = new CorrelationId(baseBytes);

            id1.ToString().Should().Be(id1.Id.ToString());
        }
Пример #6
0
 public void WriteDataTo(System.IO.BinaryWriter writer)
 {
     writer.Write((string)CorrelationId.ToString());
     writer.Write((int)Port);
     writer.Write((string)NUnitTestRunner);
     writer.Write((string)MsTestRunner);
     writer.Write((bool)LoggingEnabled);
     writer.Write(StartedPaused);
 }
Пример #7
0
        private IBasicProperties CreateProperties()
        {
            var properties = Channel.CreateBasicProperties();

            properties.Headers       = new Dictionary <string, object>();
            properties.CorrelationId = CorrelationId.ToString();
            properties.ReplyTo       = ReplyQueueName;

            return(properties);
        }
 public void WriteDataTo(BinaryWriter writer)
 {
     writer.Write(CorrelationId.ToString());
     writer.Write(ProcessId);
     writer.Write(Port);
     writer.Write(NUnitTestRunner);
     writer.Write(MsTestRunner);
     writer.Write(LoggingEnabled);
     writer.Write(StartedPaused);
 }
Пример #9
0
        public void should_log_server_request_with_content()
        {
            var @event = (HttpServerRequest)StubHttpServerEventCallback.Events[0];

            @event.EventType.ShouldBe("HttpServerRequest");
            @event.Uri.ShouldBe("/get-ids-from-context");
            @event.Method.ShouldBe("GET");
            @event.Tags.ShouldContainKeyAndValue("requestId", RequestId.ToString());
            @event.Tags.ShouldContainKeyAndValue("correlationId", CorrelationId.ToString());
            @event.Tags.ShouldContainKeyAndValue("sessionId", "(Not available)");
        }
Пример #10
0
        public async Task LogRequestAsync(HttpRequest request)
        {
            RequestLine = $"{request.Method} {request.Path} {request.Headers["Authorization"]} { GetCustomHeader(request.Headers)}".Trim();

            if (!request.Headers.ContainsKey("CorrelationId"))
            {
                request.Headers.Add("CorrelationId", new[] { CorrelationId.ToString() });
            }

            Body = await new StreamReader(request.Body).ReadToEndAsync();
            Body = Body.TrimJson();

            base.LogRequestSync();
        }
        public async Task setup_scenario()
        {
            var headers = new Dictionary <string, string>
            {
                { "request-id", RequestId.ToString() },
                { "correlation-id", CorrelationId.ToString() },
                { "session-id", SessionId.ToString() }
            };

            var response = await TestHost.GetAsync("/get-ids-from-context", headers);

            var content = await response.Content.ReadAsStringAsync();

            _idsFromContext = JObject.Parse(content);
        }
 /// <summary>
 /// Method to log details related to request such as time taken for method execution along
 /// with user id and corretion id. Use this method only in OnActionExecuted to capture
 /// desired details
 /// </summary>
 /// <param name="userId"></param>
 /// <param name="startTime"></param>
 /// <param name="endTime"></param>
 /// <param name="className"></param>
 /// <param name="methodName"></param>
 public void LogRequestDetails(string userId, DateTime startTime, DateTime endTime, string controllerName, string methodName)
 {
     try
     {
         var    executionTime    = endTime - startTime;
         string formattedMessage = String.Format("LogFileName - {0}, UserId - {1}. Correlation Id - {2}. Controller Name - {3}. Method Name - {4}. Method call started at - {5}. Method call end at - {6}. Method execution time - {7} ", logFileName, string.IsNullOrEmpty(userId) ? "Not Available" : userId, CorrelationId, controllerName, methodName, startTime.ToString("HH:mm:ss.fff"), endTime.ToString("HH:mm:ss.fff"), executionTime);
         TelemetryClient.Context.Operation.Id = CorrelationId.ToString();
         TelemetryClient.TrackTrace(formattedMessage, SeverityLevel.Information);
         TelemetryClient.Flush();
     }
     catch (Exception ex)
     {
         throw new LogMangerException(nameof(ErrorCodeMessages.LoggerError106) + ": " + ErrorCodeMessages.LoggerError106, ex);
     }
 }
Пример #13
0
        private Task OnReply(object sender, BasicDeliverEventArgs args)
        {
            if (args.BasicProperties.CorrelationId != CorrelationId.ToString())
            {
                return(Task.CompletedTask);
            }

            var msgType = GetMessageType(args);

            switch (msgType)
            {
            case MessageType.RegisterOrder:
                var message = Message.Parse <RegisterOrder>(args.Body.ToArray());
                _hubContext.Clients.Group(message.OrderId.ToString())
                .SendAsync(OrderFulfillmentMessages.Registered);
                break;

            case MessageType.FinalizingError:
                var error = Message.Parse <FinalizingError>(args.Body.ToArray());
                _hubContext.Clients.Group(error.OrderId.ToString()).SendAsync(
                    OrderFulfillmentMessages.Failed,
                    error.ErrorMessage);
                break;

            case MessageType.FinalizingSuccess:
                var success = Message.Parse <FinalizingSuccess>(args.Body.ToArray());
                _hubContext.Clients.Group(success.OrderId.ToString()).SendAsync(
                    OrderFulfillmentMessages.Completed,
                    success.DeliveryDateTime);
                break;

            case MessageType.Error:
                var defaultError = Message.Parse <Error>(args.Body.ToArray());
                _hubContext.Clients.Group(defaultError.OrderId.ToString()).SendAsync(
                    OrderFulfillmentMessages.Error,
                    defaultError.ErrorMessage);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(Task.CompletedTask);
        }
Пример #14
0
        private bool SendMail(UCore.Settings settings, List <UCore.Entry> entries)
        {
            if (entries == null || settings == null)
            {
                return(false);
            }

            string        subject = UCore.Resource.Read("MailSubject") + SPContext.Current.Web.Title;
            StringBuilder message = new StringBuilder();

            //message.AppendLine();
            message.AppendFormat("<b>{3}</b> {0}<br><b>{4}</b> {1}<br><b>{5}</b> {2}<br><br>{6}<br>",
                                 SPContext.Current.Web.CurrentUser.Email,
                                 CurrentUrl.ToString(),
                                 CorrelationId.ToString("D"),
                                 UCore.Resource.Read("MailFrom"),
                                 UCore.Resource.Read("MailSite"),
                                 UCore.Resource.Read("MailId"),
                                 UCore.Resource.Read("MailTitle"));
            message.AppendFormat("<table border=\"1\" cellpadding=\"4\" style=\"border-collapse:collapse\"><thead><tr><th width=\"10%\">{0}</th><th>{1}</th></tr></thead><tbody>",
                                 UCore.Resource.Read("ULSLevel"),
                                 UCore.Resource.Read("ULSMessage"));
            for (int x = 0; x < entries.Count && x < UCore.ULS.Limit - 1; x++)
            {
                var entry = entries[x];
                message.AppendFormat("<tr><td valign=\"top\">{0}</td><td valign=\"top\">{1}</td></tr>", entry.Severity, entry.Message);
            }
            message.Append("</tbody></table>");
            if (entries.Count >= UCore.ULS.Limit)
            {
                message.Append("<div>...</div>");
            }

            try
            {
                return(SPUtility.SendEmail(SPContext.Current.Web, true, false, settings.MailTo, subject, message.ToString()));
            }
            catch (SPException ex)
            {
                UCore.Logger.WriteLog(Core.Logger.Category.High, "ULSErrorNotification", ex.Message);
                return(false);
            }
        }
Пример #15
0
        public void TestProvidedMethods()
        {
            var i1 = Guid.NewGuid();
            var i2 = Guid.NewGuid();

            var c1 = new CorrelationId(i1);
            var c2 = new CorrelationId(i2);

            Assert.AreEqual(i1.CompareTo(i2), c1.CompareTo(c2));                    // Compare correlation id and correlation id
            Assert.AreEqual(i1.CompareTo(i2), c1.CompareTo(i2));                    // Compare correlation id and Guid
            Assert.AreEqual(i1.CompareTo((object)i2), c1.CompareTo((object)c2));    // Compare correlation id and object cid
            Assert.AreEqual(i1.CompareTo((object)i2), c1.CompareTo((object)i2));    // Compare correlation id and object Guid

            Assert.IsTrue(c1.Equals(new CorrelationId(i1)));                        // Equals correlation id and correlation id
            Assert.IsFalse(c1.Equals(new CorrelationId(i2)));                       // Not equals correlation id and correlation id
            Assert.IsTrue(c1.Equals((object)new CorrelationId(i1)));                // Equals correlation id and object correlation id
            Assert.IsFalse(c1.Equals((object)new CorrelationId(i2)));               // Not equals correlation id and object correlation id

            Assert.IsTrue(c1.Equals(i1));                                           // Equals correlation id and Guid
            Assert.IsFalse(c1.Equals(i2));                                          // Not equals correlation id and Guid
            Assert.IsFalse(c1.Equals((object)i1));                                  // Not equals correlation id and object Guid
            Assert.IsFalse(c1.Equals((object)i2));                                  // Not equals correlation id and object Guid

            Assert.AreEqual(i1.GetHashCode(), c1.GetHashCode());                    // GetHashCode
            Assert.AreNotEqual(i2.GetHashCode(), c1.GetHashCode());                 
            Assert.AreEqual(c1.GetHashCode(), c1.GetHashCode());                    
            Assert.AreNotEqual(c2.GetHashCode(), c1.GetHashCode());                 

            CollectionAssert.AreEqual(i1.ToByteArray(), c1.ToByteArray());          // To byte array
            CollectionAssert.AreNotEqual(i2.ToByteArray(), c1.ToByteArray());
            CollectionAssert.AreEqual(i2.ToByteArray(), c2.ToByteArray());
            CollectionAssert.AreNotEqual(i1.ToByteArray(), c2.ToByteArray());                 


            Assert.AreEqual(i1.ToString(), c1.ToString());                          // To string
            Assert.AreNotEqual(i2.ToString(), c1.ToString());                       
            Assert.AreEqual(i2.ToString(), c2.ToString());                          
            Assert.AreNotEqual(i1.ToString(), c2.ToString());                       
                                                                                    
            Assert.AreEqual(i1.ToString("N"), c1.ToString("N"));                    // To string with format
            Assert.AreNotEqual(i2.ToString("N"), c1.ToString("N"));                 
            Assert.AreEqual(i2.ToString("N"), c2.ToString("N"));                    
            Assert.AreNotEqual(i1.ToString("N"), c2.ToString("N"));                 
                                                                                    
            var c = CultureInfo.CurrentCulture;                                     
            Assert.AreEqual(i1.ToString("D", c), c1.ToString("D", c));              // To string with format and provider
            Assert.AreNotEqual(i2.ToString("D", c), c1.ToString("D", c));           
            Assert.AreEqual(i2.ToString("D", c), c2.ToString("D", c));              
            Assert.AreNotEqual(i1.ToString("D", c), c2.ToString("D", c));           
        }
 public void LogWarning(string message, Dictionary <string, string> properties)
 {
     try
     {
         if (IsLogWarn)
         {
             TelemetryClient.Context.Operation.Id = CorrelationId.ToString();
             TelemetryClient.TrackTrace("LogFileName- " + logFileName + ":" + message, SeverityLevel.Warning, properties);
             TelemetryClient.Flush();
         }
     }
     catch (LogMangerException)
     {
         throw;
     }
     catch (Exception innerException)
     {
         throw new LogMangerException(nameof(ErrorCodeMessages.LoggerError106) + ": " + ErrorCodeMessages.LoggerError106, innerException);
     }
 }
Пример #17
0
 public void WriteDataTo(BinaryWriter writer)
 {
     writer.Write(CorrelationId.ToString());
     writer.Write(Signature);
     writer.Write(NumberOfTests);
     writer.Write(RiskMetric);
     writer.Write(Found);
     writer.Write(NodeCount);
     writer.Write(Descriptors.Count);
     writer.Write(TotalTime);
     writer.Write(TotalTimeUnder);
     writer.Write(AverageTime);
     writer.Write(AverageTimeUnder);
     writer.Write(CalledCount);
     writer.Write(GraphScore);
     writer.Write(TestsScore);
     writer.Write(Complexity);
     foreach (var t in Descriptors)
     {
         writer.Write(t);
     }
 }
 public void LogError(string message)
 {
     try
     {
         if (IsLogError)
         {
             TelemetryClient.Context.Operation.Id = CorrelationId.ToString();
             ExceptionTelemetry exceptionTelementry = new ExceptionTelemetry();
             exceptionTelementry.Exception = new Exception("LogFileName- " + logFileName + ":" + message);
             exceptionTelementry.Properties.Add("PreciseTimeStamp", DateTime.Now.Ticks.ToString());
             TelemetryClient.TrackException(exceptionTelementry);
             TelemetryClient.Flush();
         }
     }
     catch (LogMangerException)
     {
         throw;
     }
     catch (Exception innerException)
     {
         throw new LogMangerException(nameof(ErrorCodeMessages.LoggerError106) + ": " + ErrorCodeMessages.LoggerError106, innerException);
     }
 }
 public void returns_ids_from_headers()
 {
     _idsFromContext["requestId"].Value <string>().ShouldBe(RequestId.ToString());
     _idsFromContext["correlationId"].Value <string>().ShouldBe(CorrelationId.ToString());
     _idsFromContext["sessionId"].Value <string>().ShouldBe(SessionId.ToString());
 }
Пример #20
0
 public override string ToString()
 {
     return("Id " + CorrelationId.ToString() + " NoddyText = '" + NoddyText + "' BigEarText = '" + BigEarText + "' CurrentState '" + CurrentStateName + "'");
 }
Пример #21
0
        public void TransactionCreated(int cycleId, TransactionType type, uint256 txId, CorrelationId correlation)
        {
            var record = new TrackerRecord()
            {
                Cycle           = cycleId,
                RecordType      = RecordType.Transaction,
                TransactionType = type,
                TransactionId   = txId,
                Correlation     = correlation,
            };

            bool isNew = true;

            //The
            var uniqueKey = NBitcoin.Crypto.Hashes.Hash256(txId.ToBytes().Concat(correlation.ToBytes()).ToArray()).GetLow64();

            _Repo.UpdateOrInsert(GetCyclePartition(cycleId), uniqueKey.ToString(), record, (a, b) =>
            {
                isNew = false;
                return(b);
            });
            _Repo.UpdateOrInsert("Search", "t:" + txId.ToString(), cycleId, (a, b) => b);

            if (isNew)
            {
                Logs.Tracker.LogInformation($"Tracking transaction {type} of cycle {cycleId} with correlation {correlation.ToString(false)} ({txId})");
            }
        }
Пример #22
0
 public void returns_ids_from_context()
 {
     _ids["requestId"].Value <string>().ShouldBe(RequestId.ToString());
     _ids["correlationId"].Value <string>().ShouldBe(CorrelationId.ToString());
     _ids["sessionId"].Value <string>().ShouldBe("(Not available)");
 }
Пример #23
0
        public void AddressCreated(int cycleId, TransactionType type, Script scriptPubKey, CorrelationId correlation)
        {
            var record = new TrackerRecord()
            {
                Cycle           = cycleId,
                RecordType      = RecordType.ScriptPubKey,
                TransactionType = type,
                ScriptPubKey    = scriptPubKey,
                Correlation     = correlation
            };

            bool isNew = true;

            _Repo.UpdateOrInsert(GetCyclePartition(cycleId), Rand(), record, (a, b) =>
            {
                isNew = false;
                return(b);
            });
            _Repo.UpdateOrInsert("Search", "t:" + scriptPubKey.Hash.ToString(), cycleId, (a, b) => b);

            if (isNew)
            {
                Logs.Tracker.LogInformation($"Tracking address {type} of cycle {cycleId} with correlation {correlation.ToString(false)} ({scriptPubKey.GetDestinationAddress(Network)})");
            }
        }
Пример #24
0
 public void WriteDataTo(BinaryWriter writer)
 {
     writer.Write(CorrelationId.ToString());
     writer.Write(Port);
     writer.Write(WatchPath);
 }
Пример #25
0
        public override string ToString()
        {
            if ((Details == null) || (!Details.Any()))
            {
                return(string.Format("<result type='{0}' timeStamp='{1}' correlationId='{2}'><message>{3}</message></result>", Outcome, DateTime.UtcNow, CorrelationId.ToString(), Message));
            }
            else
            {
                StringBuilder builder = new StringBuilder();

                builder.AppendFormat("<result type='{0}' timeStamp='{1}' correlationId='{2}'><message>{3}</message>", Outcome, DateTime.UtcNow, CorrelationId.ToString(), Message);
                builder.Append("<details>");

                foreach (var entry in Details)
                {
                    builder.AppendFormat("<detail key='{0}'>{1}</detail>", entry.Key, entry.Value);
                }

                builder.Append("</details>");
                builder.Append("</result>");

                return(builder.ToString());
            }
        }