protected virtual async Task <HttpResponseMessage> TracingSendAsync(ISpan span, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IEnumerable <string> traceIdVals = null;

            if (request.Headers.TryGetValues(prefix_spanId, out traceIdVals))
            {
                request.Headers.Remove(prefix_spanId);
                request.Headers.TryAddWithoutValidation(prefix_spanId, span.SpanContext.SpanId);
            }

            span.Tags.Client().Component("HttpClient")
            .HttpMethod(request.Method.Method)
            .HttpUrl(request.RequestUri.OriginalString)
            .HttpHost(request.RequestUri.Host)
            .HttpPath(request.RequestUri.PathAndQuery)
            .PeerAddress(request.RequestUri.OriginalString)
            .PeerHostName(request.RequestUri.Host)
            .PeerPort(request.RequestUri.Port);

            _tracer.Tracer.Inject(span.SpanContext, request.Headers, (c, k, v) =>
            {
                if (!c.Contains(k))
                {
                    c.Add(k, v);
                }
            });

            span.Log(LogField.CreateNew().ClientSend());

            var responseMessage = await base.SendAsync(request, cancellationToken);

            span.Log(LogField.CreateNew().ClientReceive());

            return(responseMessage);
        }
Example #2
0
        protected override async Task <HttpResponseMessage> TracingSendAsync(
            ISpan span,
            HttpRequestMessage request,
            CancellationToken cancellationToken,
            Action <string> addTraceIdToRepo,
            Func <HttpRequestMessage, CancellationToken, Task <HttpResponseMessage> > baseSendAsync)
        {
            if (request.Headers.Contains(PrefixSpanId))
            {
                request.Headers.Remove(PrefixSpanId);
                request.Headers.TryAddWithoutValidation(PrefixSpanId, span.SpanContext.SpanId);
            }

            addTraceIdToRepo(span.SpanContext.TraceId);

            span.Log(LogField.CreateNew().ClientSend());

            var responseMessage = await baseSendAsync(request, cancellationToken);

            span.Log(LogField.CreateNew().ClientReceive());

            await Task.Run(() => SendSpan(span, request, responseMessage));

            return(responseMessage);
        }
        public void Request(ref Message req)
        {
            if (!(_configuration.Streaming || _configuration.Verbose))
            {
                return;
            }

            const int maxBufferSize = int.MaxValue;
            var       buffer        = req.CreateBufferedCopy(maxBufferSize);

            try
            {
                var data = buffer.CreateMessage().ToString();
                _span.Log(new Dictionary <string, object>
                {
                    { LogFields.Event, "WCF request" },
                    { "data", data }
                });
            }
            finally
            {
                req = buffer.CreateMessage();
                buffer.Close();
            }
        }
Example #4
0
 public virtual ISpan Log(IEnumerable <KeyValuePair <string, object> > fields)
 {
     _span.Log(fields);
     _hooks.OnSpanLog(_span, _operationName, DateTimeOffset.Now, fields.Select(f => new LogKeyValue {
         key = f.Key, value = f.Value
     }).ToArray());
     return(this);
 }
        public async Task <ActionResult <string> > Get(string name, CancellationToken ct)
        {
            using (IScope scope = _tracer.BuildActiveSpan("Hello-get"))
            {
                ISpan span = scope.Span;

                span.LogMessage("baggage", span.GetBaggageItem("baggage"));

                // Here you can have TaskCanceledException, which will be handled by ExceptionHandlingMiddleware.
                await Task.Delay(_random.Next(100, 250), ct);

                HttpStatusCode selectedStatusCode = _httpStatusCodes[_random.Next(_httpStatusCodes.Length)];

                span.LogMessage("name", name);
                span.Log($"Selected status code: {selectedStatusCode}");

                // --> Return OK.
                if (selectedStatusCode == HttpStatusCode.OK)
                {
                    return(Ok($"Hello {name}."));
                }

                // --> Delay.
                if (selectedStatusCode == HttpStatusCode.RequestTimeout)
                {
                    try
                    {
                        // If your method do not accept token in the argument, you can check it here beforehand.
                        ct.ThrowIfCancellationRequested();

                        await Task.Delay(5000, ct);
                    }
                    catch (OperationCanceledException)
                    {
                        span.Log("The operation was canceled.");

                        return(NoContent());
                    }

                    // The timeout policy cancel this call earlier, so you won't see this line.
                    span.Log($"After the delay.");
                }

                if (selectedStatusCode == HttpStatusCode.InternalServerError)
                {
                    throw new Exception("Throw exception for test purpose.");
                }

                // --> Other returns.
                return(new ContentResult
                {
                    StatusCode = (int)selectedStatusCode,
                    Content = $"Selected status code: {selectedStatusCode}"
                });
            }
        }
Example #6
0
        public void Params(string key, object value)
        {
            _logsDictionary.Clear();

            Assert.Empty(_logsDictionary);

            _span.Log(key, value);

            Assert.Single(_logsDictionary);
            Assert.True(_logsDictionary.ContainsKey(key));
            Assert.Equal(value, _logsDictionary[key]);
        }
Example #7
0
        public void ResponseHeader(Metadata metadata)
        {
            if (!_configuration.Verbose)
            {
                return;
            }

            _span.Log(new Dictionary <string, object>
            {
                { LogFields.Event, "Response headers received" },
                { "data", metadata }
            });
        }
Example #8
0
        public ISpan TraceError(string logMessage, IDictionary <string, object> spanLog = null, LogLevel level = LogLevel.Error, params object[] args)
        {
            ISpan activeSpan = Tracer.ActiveSpan ?? TraceOperation(logMessage);

            Logger.Log(level, logMessage, args);
            activeSpan.Log(DateTimeOffset.UtcNow, logMessage);
            if (spanLog is null)
            {
                return(activeSpan);
            }
            activeSpan.Log(DateTimeOffset.UtcNow, spanLog);
            return(activeSpan);
        }
        public async Task <IActionResult> DetermineFileTypeFromBase64([FromBody][Required] Base64Request request)
        {
            _logger.LogInformation($"[{UserAgentInfo.ClientTypeString}]:: {nameof(DetermineFileTypeFromBase64)} method invoked");

            string originalStoreFilePath = string.Empty;
            string rebuiltStoreFilePath  = string.Empty;
            string fileId = string.Empty;
            CloudProxyResponseModel cloudProxyResponseModel = new CloudProxyResponseModel();

            ISpanBuilder builder = _tracer.BuildSpan("Post::Data");
            ISpan        span    = builder.Start();

            // Set some context data
            span.Log("File Type Detection base64");
            span.SetTag("Jaeger Testing Client", "POST api/FileTypeDetection/base64 request");

            try
            {
                if (!ModelState.IsValid)
                {
                    cloudProxyResponseModel.Errors.AddRange(ModelState.Values.SelectMany(v => v.Errors).Select(x => x.ErrorMessage));
                    return(BadRequest(cloudProxyResponseModel));
                }

                if (!_fileUtility.TryGetBase64File(request.Base64, out byte[] file))
Example #10
0
        /// <summary>
        /// Single log-value version of <see cref="LogWithMemberInfo(ISpan,IEnumerable{KeyValuePair{string,object}},CallerInfoLogFlags,string,string,string,int)"/>
        /// </summary>
        public static ISpan LogWithMemberInfo(
            this ISpan span,
            string fieldKey,
            object fieldValue,
            CallerInfoLogFlags logFlags          = CallerInfoLogFlags.AllInformation,
            string memberNameLogKey              = Constants.CallerMemberNameLogKey,
            string lineNumberLogKey              = Constants.CallerMemberLineNumberLogKey,
            [CallerMemberName] string memberName = null,
            [CallerLineNumber] int lineNumber    = -1)
        {
            var fields = new[]
            {
                new KeyValuePair <string, object>(fieldKey, fieldValue),
            };

            var memberFields = CreateFields(
                logFlags,
                memberNameLogKey,
                lineNumberLogKey,
                memberName,
                lineNumber);

            return(span
                   .Log(fields.Concat(memberFields)));
        }
Example #11
0
        public async Task <IActionResult> RebuildFromFormFile([FromForm][Required] IFormFile file)
        {
            bool zipRequest = Request.Path.ToString().ToLower().EndsWith(Constants.Endpoints.ZIP_FILE);

            _logger.LogInformation($"[{UserAgentInfo.ClientTypeString}]:: {nameof(RebuildFromFormFile)} method invoked");

            string originalStoreFilePath = string.Empty;
            string rebuiltStoreFilePath  = string.Empty;
            string fileId                      = string.Empty;
            string tempFolderPath              = Path.Combine(Constants.VAR_PATH, $"{Guid.NewGuid()}");
            string extractedFolderPath         = Path.Combine(tempFolderPath, $"{Guid.NewGuid()}");
            string extractedRebuildZipFilePath = Path.Combine(tempFolderPath, $"{Guid.NewGuid()}");
            string extractedRebuildFolderPath  = Path.Combine(tempFolderPath, $"{Guid.NewGuid()}");
            CloudProxyResponseModel cloudProxyResponseModel = new CloudProxyResponseModel();

            ISpanBuilder builder = _tracer.BuildSpan("Post::Data");
            ISpan        span    = builder.Start();

            // Set some context data
            span.Log("Rebuild file");
            span.SetTag("Jaeger Testing Client", "POST api/Rebuild/file request");

            try
            {
                if (!_fileUtility.TryReadFormFile(file, out byte[] fileBytes))
Example #12
0
        public static ISpan LogMessage(
            [NotNull] this ISpan span,
            string messageFormat,
            [NotNull] params object[] parameters)
        {
            var logFields = new KeyValuePair <string, object> [parameters.Length + 1];

            logFields[0] = new KeyValuePair <string, object>(MessageFormatKey, messageFormat);
            for (int i = 0; i < parameters.Length; i++)
            {
                string key;
                if (i < SavedMessageParameterKeyCount)
                {
                    key = SavedMessageParameterKeys[i];
                }
                else
                {
                    key = MessageParameterKeyPrefix + i;
                }
                logFields[i + 1] = new KeyValuePair <string, object>(key, parameters[i]);
            }

            return(span
                   .Log(logFields));
        }
Example #13
0
        private void LogPostHandleMessage(CorrelationContext context, string messageName, ISpan span, string retryMessage)
        {
            var postLogMessage = $"Handled a message: '{messageName}'" +
                                 $"with correlationId: {context.Id}. {retryMessage}";

            _logger.LogInformation(postLogMessage);
            span.Log(postLogMessage);
        }
Example #14
0
        private void LogPreHandleMessage(CorrelationContext context, string messageName, ISpan span, string retryMessage)
        {
            var logMessage = $"Handling a message: '{messageName}'" +
                             $"with correlationId: '{context.Id}'. {retryMessage}";

            _logger.LogInformation(logMessage);
            span.Log(logMessage);
        }
Example #15
0
        public static void SetException(this ISpan span, Exception e)
        {
            if (span == null || e == null)
            {
                return;
            }

            span.Log(CreateSpanErrorAttributes(e));
        }
Example #16
0
        public static ISpan WithGraphQLTags(this ISpan span, IResolveFieldContext <object> context)
        {
            if (context.Arguments == null || context.Arguments.Count == 0)
            {
                return(span);
            }

            foreach (var argument in context.Arguments)
            {
                if (argument.Value is List <object> list)
                {
                    span.SetTag($"collection.{argument.Key}", true);

                    if (list.Count == 1)
                    {
                        span.SetTag(argument.Key, list[0].ToString());
                    }
                    else
                    {
                        span.Log(list.Select(x => KeyValuePair.Create(argument.Key, x)));
                    }
                }
                else if (argument.Value is object[] array)
                {
                    span.SetTag($"collection.{argument.Key}", true);

                    if (array.Count() == 1)
                    {
                        span.SetTag(argument.Key, array[0].ToString());
                    }
                    else
                    {
                        span.Log(array.Select(x => KeyValuePair.Create(argument.Key, x)));
                    }
                }
                else
                {
                    span.SetTag(argument.Key, argument.Value.ToString());
                }
            }

            return(span);
        }
Example #17
0
        public static void FinalizeTrace(this ISpan spanToFinish, IDictionary <string, object> log)
        {
            if (log is null)
            {
                spanToFinish.Finish();
            }

            spanToFinish.Log(DateTimeOffset.UtcNow, log);
            spanToFinish.Finish();
        }
        public WcfTraceLogger(ISpan span, TracingConfiguration configuration)
        {
            _span          = span;
            _configuration = configuration;

            if (_configuration.Verbose)
            {
                _span.Log("Started call");
            }
        }
        public void Log_Logs_LogsAreProperlySet()
        {
            ISpan span = GetScope("Op1").Span;

            span.Log("Some Event");
            Thread.Sleep(TimeSpan.FromMilliseconds(15));

            var doubleDict = new Dictionary <string, object>()
            {
                { "event name", 123.45 }
            };

            span.Log(doubleDict);
            Thread.Sleep(TimeSpan.FromMilliseconds(15));

            var ex     = new Exception("Some Exception");
            var exDict = new Dictionary <string, object>()
            {
                { "another event name", ex }
            };

            span.Log(exDict);
            Thread.Sleep(TimeSpan.FromMilliseconds(15));

            var now  = DateTime.UtcNow.AddMilliseconds(1); // Add 1 msec to ensure different time than calls above.
            var then = now.AddMilliseconds(2);             // TODO: currently if Log receives same timestamp previous are overwritten.

            span.Log(now, "Another Event");
            span.Log(then, exDict);

            var otSpan = (OpenTracingSpan)span;
            var logs   = otSpan.Span.Logs;

            var sortedLogs = new SortedDictionary <DateTimeOffset, Dictionary <string, string> >(logs);

            Assert.Equal("Some Event", sortedLogs.ElementAt(0).Value["event"]);
            Assert.Equal("123.45", sortedLogs.ElementAt(1).Value["event name"]);
            Assert.Equal(ex.ToString(), sortedLogs.ElementAt(2).Value["another event name"]);
            Assert.Equal("Another Event", sortedLogs[now]["event"]);
            Assert.Equal(ex.ToString(), sortedLogs[then]["another event name"]);
            Assert.True(logs.Count == 5);
        }
 public static ISpan Log(
     this ISpan span,
     string key,
     object value)
 {
     return(span
            .Log(new[]
     {
         new KeyValuePair <string, object>(key, value),
     }));
 }
 public static ISpan Log(
     this ISpan span,
     KeyValuePair <string, object> field)
 {
     return(span
            .Log(
                new[]
     {
         field
     }));
 }
Example #22
0
        public static void SetException(this ISpan span, Exception exception)
        {
            span.Log(new Dictionary <string, object>(3)
            {
                { LogFields.Event, Tags.Error.Key },
                { LogFields.ErrorKind, exception.GetType().Name },
                { LogFields.ErrorObject, exception }
            });

            span.SetTag(Tags.Error, true);
        }
Example #23
0
        protected virtual async Task <HttpResponseMessage> TracingSendAsync(ISpan span, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            span.Tags.Client().Component("HttpClient")
            .HttpMethod(request.Method.Method)
            .HttpUrl(request.RequestUri.OriginalString)
            .HttpHost(request.RequestUri.Host)
            .HttpPath(request.RequestUri.PathAndQuery)
            .PeerAddress(request.RequestUri.OriginalString)
            .PeerHostName(request.RequestUri.Host)
            .PeerPort(request.RequestUri.Port);

            _tracer.Tracer.Inject(span.SpanContext, request.Headers, (c, k, v) => c.Add(k, v));

            span.Log(LogField.CreateNew().ClientSend());

            var responseMessage = await base.SendAsync(request, cancellationToken);

            span.Log(LogField.CreateNew().ClientReceive());

            return(responseMessage);
        }
Example #24
0
 public static ISpan LogMessage(
     [NotNull] this ISpan span,
     string message)
 {
     return(span
            // TODO: there should be a way to pass these without the object allocation/boxing, custom struct?
            .Log(
                new[]
     {
         new KeyValuePair <string, object>(KnownLogFieldNames.Message, message)
     }));
 }
 public static ISpan Log(
     this ISpan span,
     DateTimeOffset timestamp,
     KeyValuePair <string, object> field)
 {
     return(span
            .Log(
                timestamp,
                new[]
     {
         field
     }));
 }
        public void TestSpanNotSampled()
        {
            Tracer tracer = new Tracer.Builder("fo")
                            .WithReporter(reporter)
                            .WithSampler(new ConstSampler(false))
                            .Build();
            ISpan foo = tracer.BuildSpan("foo")
                        .Start();

            foo.Log(new Dictionary <string, object>())
            .Finish();
            Assert.Empty(reporter.GetSpans());
        }
Example #27
0
        public static ISpan LogError(this ISpan span, Exception ex, string message)
        {
            span.SetTag(Tags.Error, true);

            var fields = new Dictionary <string, object>
            {
                [LogFields.Message]     = message,
                [LogFields.ErrorObject] = ex?.GetType().Name,
                ["Exception"]           = ex
            };

            return(span.Log(fields));
        }
Example #28
0
        private void HandleRegularEvent(string eventName, object untypedArg)
        {
            ISpan span = _tracer.ActiveSpan;

            if (span != null)
            {
                span.Log(GetLogFields(eventName, untypedArg));
            }
            else if (_isLogLevelTraceEnabled)
            {
                _logger.LogTrace("No ActiveSpan. Event: {ListenerName}/{Event}", _listenerName, eventName);
            }
        }
Example #29
0
        private void SetSpanException(ISpan span, JobExecutionException exception)
        {
            span.SetTag(Tags.Error, true);

            span.Log(new Dictionary <string, object>(3)
            {
                { LogFields.Event, Tags.Error.Key },
                { LogFields.ErrorKind, exception.GetType().Name },
                { LogFields.ErrorObject, options.IncludeExceptionDetails
                        ? exception
                        : (object)$"{nameof(QuartzDiagnosticOptions.IncludeExceptionDetails)} is disabled" }
            });
        }
        /// <summary>
        /// Adds information about the <paramref name="exception"/> to the given <paramref name="span"/>.
        /// </summary>
        public static void SetException(this ISpan span, Exception exception)
        {
            if (span == null || exception == null)
            {
                return;
            }

            span.Log(new Dictionary <string, object>(3)
            {
                { LogFields.Event, Tags.Error.Key },
                { LogFields.ErrorKind, exception.GetType().Name },
                { LogFields.ErrorObject, exception }
            });
        }