internal static Tracer InitializeTracer(bool enableLogsInjection)
        {
            var settings    = new TracerSettings();
            var writerMock  = new Mock <IAgentWriter>();
            var samplerMock = new Mock <ISampler>();

            settings.LogsInjectionEnabled = enableLogsInjection;

            return(new Tracer(settings, writerMock.Object, samplerMock.Object, scopeManager: null, statsd: null));
        }
        public SpanTests(ITestOutputHelper output)
        {
            _output = output;

            var settings = new TracerSettings();
            _writerMock = new Mock<IAgentWriter>();
            var samplerMock = new Mock<ISampler>();

            _tracer = new Tracer(settings, _writerMock.Object, samplerMock.Object, scopeManager: null, statsd: null);
        }
        public OpenTracingSpanTests()
        {
            var settings    = new TracerSettings();
            var writerMock  = new Mock <IAgentWriter>();
            var samplerMock = new Mock <ISampler>();

            var datadogTracer = new Tracer(settings, writerMock.Object, samplerMock.Object, null);

            _tracer = new OpenTracingTracer(datadogTracer);
        }
 public ZipkinContent(Span[][] spans, TracerSettings settings)
 {
     _spans              = spans;
     _settings           = settings;
     Headers.ContentType = new MediaTypeHeaderValue("application/json");
     if (!string.IsNullOrWhiteSpace(_settings.SignalFxAccessToken))
     {
         Headers.Add("X-Sf-Token", _settings.SignalFxAccessToken);
     }
 }
        public OpenTracingTracerTests()
        {
            var settings    = new TracerSettings();
            var writerMock  = new Mock <IAgentWriter>();
            var samplerMock = new Mock <ISampler>();

            _datadogTracer = new Tracer(settings, writerMock.Object, samplerMock.Object, scopeManager: null, statsd: null);

            _tracer = new OpenTracingTracer(_datadogTracer);
        }
        public SendTracesToZipkinCollector()
        {
            var settings = new TracerSettings();

            _httpRecorder = new RecordHttpHandler();
            var api         = new ZipkinApi(settings, _httpRecorder);
            var agentWriter = new AgentWriter(api, statsd: null, synchronousSend: false);

            _tracer = new Tracer(settings, agentWriter, sampler: null, scopeManager: null, statsd: null);
        }
        public static int RunLoggingProcedure(Action <string> logAction)
        {
#if NETFRAMEWORK
            // Set up the secondary AppDomain first
            // The plugin application we'll call was built and copied to the ApplicationFiles subdirectory
            // Create an AppDomain with that directory as the appBasePath
            var entryDirectory            = Directory.GetParent(Assembly.GetEntryAssembly().Location);
            var applicationFilesDirectory = Path.Combine(entryDirectory.FullName, "ApplicationFiles");
            var applicationAppDomain      = AppDomain.CreateDomain("ApplicationAppDomain", null, applicationFilesDirectory, applicationFilesDirectory, false);
#endif

            // Set up Tracer and start a trace
            // Do not explicitly set LogsInjectionEnabled = true, use DD_LOGS_INJECTION environment variable to enable
            var settings = TracerSettings.FromDefaultSources();
            settings.Environment ??= "dev";      // Ensure that we have an env value. In CI, this will automatically be assigned. Later we can test that everything is fine when Environment=null
            settings.ServiceVersion ??= "1.0.0"; // Ensure that we have an env value. In CI, this will automatically be assigned. Later we can test that everything is fine when when ServiceVersion=null
            Tracer.Configure(settings);

            try
            {
                logAction($"{ExcludeMessagePrefix}Entering Datadog scope.");
                using (var scope = Tracer.Instance.StartActive("transaction"))
                {
                    // In the middle of the trace, make a call across AppDomains
                    // Unless handled properly, this can cause the following error due
                    // to the way log4net stores "AsyncLocal" state in the
                    // System.Runtime.Remoting.Messaging.CallContext:
                    // System.Runtime.Serialization.SerializationException: Type is not resolved for member 'log4net.Util.PropertiesDictionary,log4net, Version=2.0.12.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a'.
#if NETFRAMEWORK
                    logAction("Calling the PluginApplication.Program in a separate AppDomain");
                    AppDomainProxy.Call(applicationAppDomain, "PluginApplication", "PluginApplication.Program", "Invoke", null);
#else
                    logAction("Skipping the cross-AppDomain call on .NET Core");
#endif
                }

                logAction($"{ExcludeMessagePrefix}Exited Datadog scope.");
#if NETFRAMEWORK
                AppDomain.Unload(applicationAppDomain);
#endif
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                return((int)ExitCode.UnknownError);
            }

#if NETCOREAPP2_1
            // Add a delay to avoid a race condition on shutdown: https://github.com/dotnet/coreclr/pull/22712
            // This would cause a segmentation fault on .net core 2.x
            System.Threading.Thread.Sleep(5000);
#endif

            return((int)ExitCode.Success);
        }
Ejemplo n.º 8
0
        public static void AddDistributedTracing(this IServiceCollection services)
        {
            var settings = TracerSettings.FromDefaultSources();

            settings.Integrations["AdoNet"].Enabled = false;

            var tracer = new Tracer(settings);

            // set the global tracer
            Tracer.Instance = tracer;
        }
Ejemplo n.º 9
0
        static GraphQLBenchmark()
        {
            var settings = new TracerSettings
            {
                StartupDiagnosticLogEnabled = false
            };

            Tracer.UnsafeSetTracerInstance(new Tracer(settings, new DummyAgentWriter(), null, null, null));

            new GraphQLBenchmark().ExecuteAsync();
        }
        public void ReplaceLocalhost(string original, string expected)
        {
            var settings = new NameValueCollection
            {
                { ConfigurationKeys.AgentUri, original }
            };

            var tracerSettings = new TracerSettings(new NameValueConfigurationSource(settings));

            Assert.Equal(expected, tracerSettings.Exporter.AgentUri.ToString());
        }
Ejemplo n.º 11
0
        public SendTracesToAgent()
        {
            var settings = new TracerSettings();

            var endpoint = new Uri("http://localhost:8126");

            _httpRecorder = new RecordHttpHandler();
            var api         = new Api(endpoint, apiRequestFactory: null, statsd: null);
            var agentWriter = new AgentWriter(api, new NullMetrics());

            _tracer = new Tracer(settings, plugins: null, agentWriter, sampler: null, scopeManager: null, statsd: null);
        }
Ejemplo n.º 12
0
        public SendTracesToZipkinCollector()
        {
            var settings = new TracerSettings()
            {
                AgentUri = new System.Uri("http://localhost:9411/api/v2/spans")
            };

            var api         = new ZipkinApi(settings);
            var agentWriter = new AgentWriter(api, statsd: null);

            _tracer = new Tracer(settings, agentWriter, sampler: null, scopeManager: null, statsd: null);
        }
Ejemplo n.º 13
0
        static Common()
        {
            var settings = TracerSettings.FromDefaultSources();

            settings.TraceBufferSize = 1024 * 1024 * 45; // slightly lower than the 50mb payload agent limit.

            TestTracer  = new Tracer(settings);
            ServiceName = TestTracer.DefaultServiceName;

            // Preload environment variables.
            CIEnvironmentValues.DecorateSpan(null);
        }
        /// <summary>
        /// Creates an instance of <see cref="JaegerOptions"/> based on passed <see cref="FromTracerSettings"/>.
        /// </summary>
        /// <param name="settings"><see cref="TracerSettings"/> to read configuration from</param>
        /// <returns>New instance of <see cref="JaegerOptions"/></returns>
        public static JaegerOptions FromTracerSettings(TracerSettings settings)
        {
            var agentHost = settings.ConfigurationSource?.GetString(ConfigurationKeys.JaegerExporterAgentHost) ?? "localhost";
            var agentPort = settings.ConfigurationSource?.GetInt32(ConfigurationKeys.JaegerExporterAgentPort) ?? 6831;

            return(new JaegerOptions
            {
                Host = agentHost,
                Port = agentPort,
                ServiceName = settings.ServiceName
            });
        }
        internal static Tracer InitializeTracer(bool enableLogsInjection)
        {
            var settings    = new TracerSettings();
            var writerMock  = new Mock <IAgentWriter>();
            var samplerMock = new Mock <ISampler>();

            settings.LogsInjectionEnabled = enableLogsInjection;
            settings.ServiceVersion       = "custom-version";
            settings.Environment          = "custom-env";

            return(new Tracer(settings, writerMock.Object, samplerMock.Object, scopeManager: null, statsd: null));
        }
        public void ParseHttpCodes(string original, string expected)
        {
            var tracerSettings = new TracerSettings();

            bool[]   errorStatusCodesArray = tracerSettings.ParseHttpCodesToArray(original);
            string[] expectedKeysArray     = expected.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);

            foreach (var value in expectedKeysArray)
            {
                Assert.True(errorStatusCodesArray[int.Parse(value)]);
            }
        }
        public void JsonConfigurationSource_BadData3(
            string value,
            Func <TracerSettings, object> settingGetter,
            object expectedValue)
        {
            IConfigurationSource source = new JsonConfigurationSource(value);
            var settings = new TracerSettings(source);

            var actualValue = settingGetter(settings);

            Assert.Equal(expectedValue, actualValue);
        }
        public SendTracesToAgent()
        {
            var settings = new TracerSettings();

            var endpoint = new Uri("http://localhost:8126");

            _httpRecorder = new RecordHttpHandler();
            var api         = new Api(endpoint, _httpRecorder);
            var agentWriter = new AgentWriter(api);

            _tracer = new Tracer(settings, agentWriter, sampler: null, scopeManager: null);
        }
Ejemplo n.º 19
0
        public void SetEnv(string env)
        {
            var settings = new TracerSettings()
            {
                Environment = env,
            };

            var  tracer = new Tracer(settings);
            Span span   = tracer.StartSpan("operation");

            Assert.Equal(env, span.GetTag(Tags.Env));
        }
Ejemplo n.º 20
0
        static SpanBenchmark()
        {
            TracerSettings.DisableSharedInstance = true;

            var settings = new TracerSettings
            {
                TraceEnabled = false,
                StartupDiagnosticLogEnabled = false
            };

            Tracer = new Tracer(settings, new DummyAgentWriter(), null, null, null);
        }
Ejemplo n.º 21
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            log4net.Config.XmlConfigurator.Configure();

            var settings = TracerSettings.FromDefaultSources();

            settings.Integrations["AdoNet"].Enabled             = false;
            settings.Integrations["AspNet"].Enabled             = true;
            settings.Integrations["AspNetMvc"].Enabled          = true;
            settings.Integrations["AspNetWebApi2"].Enabled      = true;
            settings.Integrations["Wcf"].Enabled                = true;
            settings.Integrations["HttpMessageHandler"].Enabled = true;
            settings.Integrations["WebRequest"].Enabled         = true;

            Process currentProcessInfo = System.Diagnostics.Process.GetCurrentProcess();
            var     startTime          = currentProcessInfo.StartTime;

            TimeSpan startTimeSpan         = (startTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            var      startTimeMilliseconds = Convert.ToUInt64(Math.Truncate(startTimeSpan.TotalMilliseconds));

            ILog log = log4net.LogManager.GetLogger(typeof(Tracer));

            log.Info($"Starting... {currentProcessInfo.Id.ToString()}");

            var enrichMode = ConfigurationManager.AppSettings["STS_ENRICH_MODE"];

            if (string.IsNullOrEmpty(enrichMode) || enrichMode != "OFF")
            {
                log.Info("Enriching with pid starttime hostname");
                settings.GlobalTags.Add("span.pid", currentProcessInfo.Id.ToString());
                settings.GlobalTags.Add("span.starttime", startTimeMilliseconds.ToString());
                if (!settings.GlobalTags.ContainsKey("span.hostname"))
                {
                    settings.GlobalTags.Add("span.hostname", Environment.MachineName);
                }
            }
            else
            {
                log.Info("SKIPPED enrichment on init.");
            }

            // create a new Tracer using these settings
            var tracer = new Tracer(settings);

            // set the global tracer
            Tracer.Instance = tracer;
        }
Ejemplo n.º 22
0
        private static void RunStuff(string serviceName, string operationName)
        {
            var settings = TracerSettings.FromDefaultSources();

            settings.ServiceName = serviceName;
            Tracer.Configure(settings);

            Counts[Key(serviceName, operationName)]++;

            IScope root;

            using (root = Tracer.Instance.StartActive(operationName: operationName))
            {
                Thread.Sleep(3);

                using (var sub = Tracer.Instance.StartActive(operationName: SubOperation))
                {
                    Thread.Sleep(2);

                    using (var open = Tracer.Instance.StartActive(operationName: OpenOperation))
                    {
                        Thread.Sleep(2);
                    }

                    using (var close = Tracer.Instance.StartActive(operationName: CloseOperation))
                    {
                        Thread.Sleep(1);
                    }
                }

                Thread.Sleep(3);
            }

            var metrics     = GetMetrics(root);
            var rulePsrKey  = "_dd.rule_psr";
            var limitPsrKey = "_dd.limit_psr";
            var priorityKey = "_sampling_priority_v1";

            if (!metrics.ContainsKey(rulePsrKey))
            {
                throw new Exception($"{rulePsrKey} must be set in a user defined rule.");
            }

            var priority = metrics[priorityKey];

            if (priority > 0f && !metrics.ContainsKey(limitPsrKey))
            {
                throw new Exception($"{limitPsrKey} must be set if a user defined rule is configured and the trace is sampled.");
            }

            Counts[Key(serviceName, operationName, priority)]++;
        }
        public OpenTracingSpanBuilderTests()
        {
            var settings = new TracerSettings
            {
                ServiceName = DefaultServiceName
            };

            var writerMock = new Mock<ITraceWriter>(MockBehavior.Strict);
            var samplerMock = new Mock<ISampler>();

            var datadogTracer = new Tracer(settings, plugins: null, writerMock.Object, samplerMock.Object, scopeManager: null, statsd: null);
            _tracer = new OpenTracingTracer(datadogTracer);
        }
        static HttpClientBenchmark()
        {
            var settings = new TracerSettings
            {
                StartupDiagnosticLogEnabled = false
            };

            Tracer.UnsafeSetTracerInstance(new Tracer(settings, new DummyAgentWriter(), null, null, null));

            var bench = new HttpClientBenchmark();

            bench.SendAsync();
        }
        public void CreateOutboundHttpScope_Null_ResourceUri()
        {
            // Set up Tracer
            var settings    = new TracerSettings();
            var writerMock  = new Mock <IAgentWriter>();
            var samplerMock = new Mock <ISampler>();
            var tracer      = new Tracer(settings, writerMock.Object, samplerMock.Object, scopeManager: null, statsd: null);

            using (var automaticScope = ScopeFactory.CreateOutboundHttpScope(tracer, "GET", null, IntegrationId.HttpMessageHandler, out _))
            {
                Assert.Equal(expected: "GET ", actual: automaticScope.Span.ResourceName);
            }
        }
        public void CleanUri_ResourceName(string uri, string method, string expected)
        {
            // Set up Tracer
            var settings    = new TracerSettings();
            var writerMock  = new Mock <IAgentWriter>();
            var samplerMock = new Mock <ISampler>();
            var tracer      = new Tracer(settings, writerMock.Object, samplerMock.Object, scopeManager: null, statsd: null);

            using (var automaticScope = ScopeFactory.CreateOutboundHttpScope(tracer, method, new Uri(uri), IntegrationId.HttpMessageHandler, out _))
            {
                Assert.Equal(expected, automaticScope.Span.ResourceName);
            }
        }
Ejemplo n.º 27
0
        static RedisBenchmark()
        {
            var settings = new TracerSettings
            {
                StartupDiagnosticLogEnabled = false
            };

            Tracer.UnsafeSetTracerInstance(new Tracer(settings, new DummyAgentWriter(), null, null, null));

            RawCommands = new[] { "Command", "arg1", "arg2" }
            .Select(Encoding.UTF8.GetBytes)
            .ToArray();
        }
Ejemplo n.º 28
0
        private void SetupDatadogTracing()
        {
            // read default configuration sources (env vars, web.config, datadog.json)
            TracerSettings settings = TracerSettings.FromDefaultSources();

            settings.LogsInjectionEnabled = true;

            // create a new Tracer using these settings
            Tracer tracer = new Tracer(settings);

            // set the global tracer
            Tracer.Instance = tracer;
        }
        static DbCommandBenchmark()
        {
            var settings = new TracerSettings
            {
                StartupDiagnosticLogEnabled = false
            };

            Tracer.UnsafeSetTracerInstance(new Tracer(settings, new DummyAgentWriter(), null, null, null));

            var bench = new DbCommandBenchmark();

            bench.ExecuteNonQuery();
        }
Ejemplo n.º 30
0
        private static IDogStatsd CreateDogStatsdClient(TracerSettings settings, string serviceName, int port)
        {
            try
            {
                var constantTags = new List <string>
                {
                    "lang:.NET",
                    $"lang_interpreter:{FrameworkDescription.Instance.Name}",
                    $"lang_version:{FrameworkDescription.Instance.ProductVersion}",
                    $"tracer_version:{TracerConstants.AssemblyVersion}",
                    $"service:{serviceName}"
                };

                if (settings.Environment != null)
                {
                    constantTags.Add($"env:{settings.Environment}");
                }

                if (settings.ServiceVersion != null)
                {
                    constantTags.Add($"version:{settings.ServiceVersion}");
                }

                var statsd = new DogStatsdService();
                if (AzureAppServices.Metadata.IsRelevant)
                {
                    // Environment variables set by the Azure App Service extension are used internally.
                    // Setting the server name will force UDP, when we need named pipes.
                    statsd.Configure(new StatsdConfig
                    {
                        ConstantTags = constantTags.ToArray()
                    });
                }
                else
                {
                    statsd.Configure(new StatsdConfig
                    {
                        StatsdServerName = settings.AgentUri.DnsSafeHost,
                        StatsdPort       = port,
                        ConstantTags     = constantTags.ToArray()
                    });
                }

                return(statsd);
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Unable to instantiate {nameof(Statsd)} client.");
                return(new NoOpStatsd());
            }
        }