public static void Initialize() { if (Interlocked.Exchange(ref _firstInitialization, 0) != 1) { // Initialize() was already called before return; } Log.Information("Initializing CI Visibility"); LifetimeManager.Instance.AddAsyncShutdownTask(ShutdownAsync); TracerSettings tracerSettings = _settings.TracerSettings; // Set the service name if empty Log.Information("Setting up the service name"); if (string.IsNullOrEmpty(tracerSettings.ServiceName)) { // Extract repository name from the git url and use it as a default service name. tracerSettings.ServiceName = GetServiceNameFromRepository(CIEnvironmentValues.Instance.Repository); } // Initialize Tracer Log.Information("Initialize Test Tracer instance"); TracerManager.ReplaceGlobalManager(tracerSettings.Build(), new CITracerManagerFactory(_settings)); }
public static IApiRequestFactory Get(ImmutableExporterSettings settings) { var strategy = settings.TracesTransport; switch (strategy) { case TracesTransportType.CustomTcpProvider: Log.Information("Using {FactoryType} for trace transport.", nameof(TcpStreamFactory)); return(new HttpStreamRequestFactory(new TcpStreamFactory(settings.AgentUri.Host, settings.AgentUri.Port), DatadogHttpClient.CreateTraceAgentClient())); case TracesTransportType.WindowsNamedPipe: Log.Information <string, string, int>("Using {FactoryType} for trace transport, with pipe name {PipeName} and timeout {Timeout}ms.", nameof(NamedPipeClientStreamFactory), settings.TracesPipeName, settings.TracesPipeTimeoutMs); return(new HttpStreamRequestFactory(new NamedPipeClientStreamFactory(settings.TracesPipeName, settings.TracesPipeTimeoutMs), DatadogHttpClient.CreateTraceAgentClient())); case TracesTransportType.UnixDomainSocket: #if NETCOREAPP3_1_OR_GREATER Log.Information <string, string, int>("Using {FactoryType} for trace transport, with Unix Domain Sockets path {Path} and timeout {Timeout}ms.", nameof(UnixDomainSocketStreamFactory), settings.TracesUnixDomainSocketPath, settings.TracesPipeTimeoutMs); return(new HttpStreamRequestFactory(new UnixDomainSocketStreamFactory(settings.TracesUnixDomainSocketPath), DatadogHttpClient.CreateTraceAgentClient())); #else Log.Error("Using Unix Domain Sockets for trace transport is only supported on .NET Core 3.1 and greater. Falling back to default transport."); goto case TracesTransportType.Default; #endif case TracesTransportType.Default: default: #if NETCOREAPP Log.Information("Using {FactoryType} for trace transport.", nameof(HttpClientRequestFactory)); return(new HttpClientRequestFactory(AgentHttpHeaderNames.DefaultHeaders)); #else Log.Information("Using {FactoryType} for trace transport.", nameof(ApiWebRequestFactory)); return(new ApiWebRequestFactory(AgentHttpHeaderNames.DefaultHeaders)); #endif } }
static DistributedTracer() { try { var parent = GetDistributedTracer(); if (parent == null) { Log.Information("Building automatic tracer"); Instance = new AutomaticTracer(); } else { var parentTracer = parent.DuckCast <IAutomaticTracer>(); Log.Information("Building manual tracer, connected to {assembly}", parent.GetType().Assembly); Instance = new ManualTracer(parentTracer); } } catch (Exception ex) { Log.Error(ex, "Error while building the tracer, falling back to automatic"); Instance = new AutomaticTracer(); } }
public static IApiRequestFactory GetDirectIntakeFactory(Uri baseEndpoint, string apiKey) { #if NETCOREAPP Log.Information("Using {FactoryType} for telemetry transport direct to intake.", nameof(HttpClientRequestFactory)); return(new HttpClientRequestFactory(baseEndpoint, TelemetryHttpHeaderNames.GetDefaultIntakeHeaders(apiKey), timeout: Timeout)); #else Log.Information("Using {FactoryType} for telemetry transport direct to intake.", nameof(ApiWebRequestFactory)); return(new ApiWebRequestFactory(baseEndpoint, TelemetryHttpHeaderNames.GetDefaultIntakeHeaders(apiKey), timeout: Timeout)); #endif }
public static IApiRequestFactory Get(ImmutableDirectLogSubmissionSettings settings) { #if NETCOREAPP Log.Information("Using {FactoryType} for log submission transport.", nameof(HttpClientRequestFactory)); return(new HttpClientRequestFactory(LogsApiHeaderNames.DefaultHeaders)); #else Log.Information("Using {FactoryType} for log submission transport.", nameof(ApiWebRequestFactory)); return(new ApiWebRequestFactory(LogsApiHeaderNames.DefaultHeaders)); #endif }
public static IApiRequestFactory Get(ImmutableDirectLogSubmissionSettings settings) { // Still quite a long time, but we could be sending a lot of data var timeout = TimeSpan.FromSeconds(15); #if NETCOREAPP Log.Information("Using {FactoryType} for log submission transport.", nameof(HttpClientRequestFactory)); return(new HttpClientRequestFactory(settings.IntakeUrl, LogsApiHeaderNames.DefaultHeaders, timeout: timeout)); #else Log.Information("Using {FactoryType} for log submission transport.", nameof(ApiWebRequestFactory)); return(new ApiWebRequestFactory(settings.IntakeUrl, LogsApiHeaderNames.DefaultHeaders, timeout: timeout)); #endif }
private static void TryAddSink <TTarget>(TTarget instance) where TTarget : ILoggerConfiguration, IDuckType { var sinkAlreadyAdded = false; // if we've already added the sink, nothing more to do. foreach (var logEventSink in instance.LogEventSinks) { if (logEventSink is DirectSubmissionSerilogSink || logEventSink?.GetType().FullName == "Serilog.Sinks.Datadog.Logs.DatadogSink") { sinkAlreadyAdded = true; break; } } if (!sinkAlreadyAdded) { var targetType = instance.Type.Assembly.GetType("Serilog.Core.ILogEventSink"); var sink = new DirectSubmissionSerilogSink( TracerManager.Instance.DirectLogSubmission.Sink, TracerManager.Instance.DirectLogSubmission.Settings.MinimumLevel); var proxy = sink.DuckImplement(targetType); instance.LogEventSinks.Add(proxy); Log.Information("Direct log submission via Serilog enabled"); } }
private void LoggingCallback( DDWAF_LOG_LEVEL level, string function, string file, int line, string message, ulong message_len) { var formattedMessage = $"{level}: [{function}]{file}({line}): {message}"; switch (level) { case DDWAF_LOG_LEVEL.DDWAF_TRACE: case DDWAF_LOG_LEVEL.DDWAF_DEBUG: _log.Debug(formattedMessage); break; case DDWAF_LOG_LEVEL.DDWAF_INFO: _log.Information(formattedMessage); break; case DDWAF_LOG_LEVEL.DDWAF_WARN: _log.Warning(formattedMessage); break; case DDWAF_LOG_LEVEL.DDWAF_ERROR: case DDWAF_LOG_LEVEL.DDWAF_AFTER_LAST: _log.Error(formattedMessage); break; default: _log.Error("[Unknown level] " + formattedMessage); break; } }
#pragma warning disable SA1202 // Elements must be ordered by access #pragma warning disable SA1204 // Static elements must appear before instance elements private static void RefreshIISPreAppState(ulong traceId) { Debug.Assert(_executingIISPreStartInit, $"{nameof(_executingIISPreStartInit)} should always be true when entering {nameof(RefreshIISPreAppState)}"); if (_performAppDomainFlagChecks) { object state = AppDomain.CurrentDomain.GetData(NamedSlotName); _executingIISPreStartInit = state is bool boolState && boolState; } else { var stackTrace = new StackTrace(false); var initialStackFrame = stackTrace.GetFrame(stackTrace.FrameCount - 1); var initialMethod = initialStackFrame.GetMethod(); _executingIISPreStartInit = initialMethod.DeclaringType.FullName.Equals("System.Web.Hosting.HostingEnvironment", StringComparison.OrdinalIgnoreCase) && initialMethod.Name.Equals("Initialize", StringComparison.OrdinalIgnoreCase); } if (_executingIISPreStartInit) { Log.Warning("IIS is still initializing the application. Automatic logs injection will be disabled until the application begins processing incoming requests. Affected traceId={0}", traceId); } else { Log.Information("Automatic logs injection has resumed, starting with traceId={0}", traceId); } }
private static bool TryLoadLibraryFromPaths(string libName, List <string> paths, out IntPtr handle) { var success = false; handle = IntPtr.Zero; foreach (var path in paths) { var libFullPath = Path.Combine(path, libName); if (!File.Exists(libFullPath)) { continue; } var loaded = NativeLibrary.TryLoad(libFullPath, out handle); if (loaded) { success = true; Log.Information($"Loaded library '{libName}' from '{path}' with handle '{handle}'"); break; } Log.Warning($"Failed to load library '{libName}' from '{path}'"); } if (!success) { Log.Warning($"Failed to load library '{libName}' from any of the following '{string.Join(", ", paths)}'"); Log.Error("AppSec could not load libddwaf native library, as a result, AppSec could not start. No security activities will be collected. Please contact support at https://docs.datadoghq.com/help/ for help."); } return(success); }
public OriginTagTraceProcessor(bool isPartialFlushEnabled, bool isAgentlessEnabled) { _isPartialFlushEnabled = isPartialFlushEnabled; _isAgentlessEnabled = isAgentlessEnabled; Log.Information("OriginTraceProcessor initialized."); }
public ProfilerStatus() { _isProfilingEnabled = EnvironmentHelpers.GetEnvironmentVariable(ConfigurationKeys.ProfilingEnabled)?.ToBoolean() ?? false; Log.Information("Continuous Profiler is {IsEnabled}.", _isProfilingEnabled ? "enabled" : "disabled"); _lockObj = new(); _isInitialized = false; }
public static KeyValuePair <string, string>[] GetTagsFromDbCommand(IDbCommand command) { var connectionString = command.Connection.ConnectionString; var cache = _cache; if (cache != null) { if (cache.TryGetValue(connectionString, out var tags)) { // Fast path: it's expected that most calls will end up in this branch return(tags); } if (cache.Count <= MaxConnectionStrings) { // Populating the cache. This path should be hit only during application warmup // ReSharper disable once ConvertClosureToMethodGroup -- Lambdas are cached by the compiler return(cache.GetOrAdd(connectionString, cs => ExtractTagsFromConnectionString(cs))); } // The assumption "connection strings are a finite set" was wrong, disabling the cache // Use atomic operation to log only once if (Interlocked.Exchange(ref _cache, null) != null) { Log.Information($"More than {MaxConnectionStrings} different connection strings were used, disabling cache"); } } // Fallback: too many different connection string, there might be a random part in them // Stop using the cache to prevent memory leaks return(ExtractTagsFromConnectionString(connectionString)); }
public static IApiRequestFactory Get(TracerSettings settings) { var strategy = settings.TracesTransport?.ToUpperInvariant(); switch (strategy) { case DatadogTcp: Log.Information("Using {FactoryType} for trace transport.", nameof(TcpStreamFactory)); return(new HttpStreamRequestFactory(new TcpStreamFactory(settings.AgentUri.Host, settings.AgentUri.Port), new DatadogHttpClient())); case DatadogNamedPipes: Log.Information <string, string, int>("Using {FactoryType} for trace transport, with pipe name {PipeName} and timeout {Timeout}ms.", nameof(NamedPipeClientStreamFactory), settings.TracesPipeName, settings.TracesPipeTimeoutMs); return(new HttpStreamRequestFactory(new NamedPipeClientStreamFactory(settings.TracesPipeName, settings.TracesPipeTimeoutMs), new DatadogHttpClient())); default: // Defer decision to Api logic return(null); } }
private IApiRequestFactory GetRequestFactory(ImmutableTracerSettings settings) { IApiRequestFactory factory = null; TimeSpan agentlessTimeout = TimeSpan.FromSeconds(15); #if NETCOREAPP Log.Information("Using {FactoryType} for trace transport.", nameof(HttpClientRequestFactory)); factory = new HttpClientRequestFactory(settings.ExporterSettings.AgentUri, AgentHttpHeaderNames.DefaultHeaders, timeout: agentlessTimeout); #else Log.Information("Using {FactoryType} for trace transport.", nameof(ApiWebRequestFactory)); factory = new ApiWebRequestFactory(settings.ExporterSettings.AgentUri, AgentHttpHeaderNames.DefaultHeaders, timeout: agentlessTimeout); #endif if (!string.IsNullOrWhiteSpace(_settings.ProxyHttps)) { var proxyHttpsUriBuilder = new UriBuilder(_settings.ProxyHttps); var userName = proxyHttpsUriBuilder.UserName; var password = proxyHttpsUriBuilder.Password; proxyHttpsUriBuilder.UserName = string.Empty; proxyHttpsUriBuilder.Password = string.Empty; if (proxyHttpsUriBuilder.Scheme == "https") { // HTTPS proxy is not supported by .NET BCL Log.Error($"HTTPS proxy is not supported. ({proxyHttpsUriBuilder})"); return(factory); } NetworkCredential credential = null; if (!string.IsNullOrWhiteSpace(userName)) { credential = new NetworkCredential(userName, password); } Log.Information("Setting proxy to: {ProxyHttps}", proxyHttpsUriBuilder.Uri.ToString()); factory.SetProxy(new WebProxy(proxyHttpsUriBuilder.Uri, true, _settings.ProxyNoProxy, credential), credential); } return(factory); }
internal static IReadOnlyCollection <IOTelExtension> TryLoadPlugins(JsonConfigurationSource pluginsConfig) { if (pluginsConfig == null) { return(ArrayHelper.Empty <IOTelExtension>()); } var targetFramework = FrameworkDescription.Instance.TargetFramework; Log.Debug("Executing plugins configuration: {0}", pluginsConfig); Log.Information("Trying to load plugins with target framework '{0}'.", targetFramework); string[] pluginFiles; try { // TODO: Here additional metadata could be loaded (eg: for security and integrity) // instead of just string path pluginFiles = pluginsConfig.GetValue <JToken>($"['{targetFramework}']").ToObject <string[]>(); } catch (ArgumentException ex) { Log.Warning(ex, "Could not parse list of plugin paths. Invalid plugin configuration provided."); return(ArrayHelper.Empty <IOTelExtension>()); } if (pluginFiles == null || !pluginFiles.Any()) { Log.Information("Skipping plugins load. Could not find any plugins with target framework '{0}'.", targetFramework); return(ArrayHelper.Empty <IOTelExtension>()); } var loadedPlugins = TryLoadPlugins(pluginFiles); Log.Information("Successfully loaded '{0}' plugin(s).", property: loadedPlugins.Count); return(loadedPlugins); }
public static IApiRequestFactory Get(ImmutableExporterSettings settings) { var strategy = settings.TracesTransport; switch (strategy) { case TracesTransportType.WindowsNamedPipe: Log.Information <string, string, int>("Using {FactoryType} for trace transport, with pipe name {PipeName} and timeout {Timeout}ms.", nameof(NamedPipeClientStreamFactory), settings.TracesPipeName, settings.TracesPipeTimeoutMs); // use http://localhost as base endpoint return(new HttpStreamRequestFactory(new NamedPipeClientStreamFactory(settings.TracesPipeName, settings.TracesPipeTimeoutMs), DatadogHttpClient.CreateTraceAgentClient(), new Uri("http://localhost"))); case TracesTransportType.Default: default: #if NETCOREAPP Log.Information("Using {FactoryType} for trace transport.", nameof(HttpClientRequestFactory)); return(new HttpClientRequestFactory(settings.AgentUri, AgentHttpHeaderNames.DefaultHeaders)); #else Log.Information("Using {FactoryType} for trace transport.", nameof(ApiWebRequestFactory)); return(new ApiWebRequestFactory(settings.AgentUri, AgentHttpHeaderNames.DefaultHeaders)); #endif } }
private static string GetImpl() { if (NativeLoader.TryGetRuntimeIdFromNative(out var runtimeId)) { Log.Information("Runtime id retrieved from native loader: " + runtimeId); return(runtimeId); } var guid = Guid.NewGuid().ToString(); Log.Debug("Unable to get the runtime id from native. Fallback to Guid.NewGuid() : {NewGuid}", guid); return(guid); }
public static CallTargetReturn <TResponse> OnMethodEnd <TTarget, TResponse>(TTarget instance, TResponse response, Exception exception, CallTargetState state) { if (!TracerManager.Instance.DirectLogSubmission.Settings.IsIntegrationEnabled(IntegrationId.Log4Net)) { return(new CallTargetReturn <TResponse>(response)); } var updatedResponse = Log4NetCommon <TResponse> .AddAppenderToResponse(response, DirectSubmissionLog4NetLegacyAppender.Instance); if (!_logWritten) { _logWritten = true; Log.Information("Direct log submission via Log4Net Legacy enabled"); } return(new CallTargetReturn <TResponse>(updatedResponse)); }
public IEnumerable <string> GetValues(string name) { // This only returns the _last_ bytes. Accessing other values is more expensive and should generally be unneccessary if (_headers.TryGetLastBytes(name, out var bytes)) { try { return(new[] { Encoding.UTF8.GetString(bytes) }); } catch (Exception ex) { Logger.Information(ex, "Could not deserialize Kafka header {headerName}", name); } } return(Enumerable.Empty <string>()); }
private static ulong ParseHexUInt64 <T>(T carrier, Func <T, string, IEnumerable <string> > getter, string headerName) { var headerValues = getter(carrier, headerName); if (headerValues.Any()) { foreach (var headerValue in headerValues) { if (ulong.TryParse(headerValue, NumberStyle, InvariantCulture, out var result)) { return(result); } } Log.Information("Could not parse {0} headers: {1}", headerName, string.Join(",", headerValues)); } return(0); }
/// <summary> /// Initializes global instrumentation values. /// </summary> public static void Initialize() { if (Interlocked.Exchange(ref _firstInitialization, 0) != 1) { // Initialize() was already called before return; } Log.Debug("Initialization started."); try { Log.Debug("Enabling by ref instrumentation."); NativeMethods.EnableByRefInstrumentation(); Log.Information("ByRef instrumentation enabled."); } catch (Exception ex) { Log.Error(ex, "ByRef instrumentation cannot be enabled: "); } try { Log.Debug("Enabling calltarget state by ref."); NativeMethods.EnableCallTargetStateByRef(); Log.Information("CallTarget State ByRef enabled."); } catch (Exception ex) { Log.Error(ex, "CallTarget state ByRef cannot be enabled: "); } try { Log.Debug("Sending CallTarget integration definitions to native library."); var payload = InstrumentationDefinitions.GetAllDefinitions(); NativeMethods.InitializeProfiler(payload.DefinitionsId, payload.Definitions); foreach (var def in payload.Definitions) { def.Dispose(); } Log.Information <int>("The profiler has been initialized with {count} definitions.", payload.Definitions.Length); } catch (Exception ex) { Log.Error(ex, ex.Message); } try { Serverless.InitIfNeeded(); } catch (Exception ex) { Serverless.Error("Error while loading Serverless definitions", ex); } try { Log.Debug("Sending CallTarget derived integration definitions to native library."); var payload = InstrumentationDefinitions.GetDerivedDefinitions(); NativeMethods.AddDerivedInstrumentations(payload.DefinitionsId, payload.Definitions); foreach (var def in payload.Definitions) { def.Dispose(); } Log.Information <int>("The profiler has been initialized with {count} derived definitions.", payload.Definitions.Length); } catch (Exception ex) { Log.Error(ex, ex.Message); } try { Log.Debug("Initializing TraceAttribute instrumentation."); var payload = InstrumentationDefinitions.GetTraceAttributeDefinitions(); NativeMethods.AddTraceAttributeInstrumentation(payload.DefinitionsId, payload.AssemblyName, payload.TypeName); Log.Information("TraceAttribute instrumentation enabled with Assembly={AssemblyName} and Type={TypeName}.", payload.AssemblyName, payload.TypeName); } catch (Exception ex) { Log.Error(ex, ex.Message); } InitializeNoNativeParts(); var tracer = Tracer.Instance; // before this line you should not call anything related to TracerManager.Instance // otherwise you can have multiple instances of Tracer if (tracer is null) { Log.Debug("Skipping TraceMethods initialization because Tracer.Instance was null after InitializeNoNativeParts was invoked"); } else { try { Log.Debug("Initializing TraceMethods instrumentation."); var traceMethodsConfiguration = tracer.Settings.TraceMethods; var payload = InstrumentationDefinitions.GetTraceMethodDefinitions(); NativeMethods.InitializeTraceMethods(payload.DefinitionsId, payload.AssemblyName, payload.TypeName, traceMethodsConfiguration); Log.Information("TraceMethods instrumentation enabled with Assembly={AssemblyName}, Type={TypeName}, and Configuration={}.", payload.AssemblyName, payload.TypeName, traceMethodsConfiguration); } catch (Exception ex) { Log.Error(ex, ex.Message); } } InitializeThreadSampling(); Log.Debug("Initialization finished."); }
public CIWriterHttpSender(IApiRequestFactory apiRequestFactory) { _apiRequestFactory = apiRequestFactory; _globalSettings = GlobalSettings.FromDefaultSources(); Log.Information("CIWriterHttpSender Initialized."); }
public static void Initialize(CancellationToken cancellationToken) { if (Interlocked.CompareExchange(ref _initialized, 1, 0) == 1) { return; } // Try to resolve System.Diagnostics.DiagnosticListener, System.Diagnostics.DiagnosticSource var diagnosticListenerType = Type.GetType("System.Diagnostics.DiagnosticListener, System.Diagnostics.DiagnosticSource", throwOnError: false); if (diagnosticListenerType is null) { // Because we cannot resolve the DiagnosticListener type we allow a later initialization. // For this case we are going to do some retries with a back-off. if (Interlocked.Decrement(ref _initializationRetries) > 0) { Task.Delay(InitializationBackoffPerRetry, cancellationToken).ContinueWith( _ => { if (cancellationToken.IsCancellationRequested) { return; } Interlocked.Exchange(ref _initialized, 0); Initialize(cancellationToken); }, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Default); } return; } // Initialize var diagnosticSourceAssemblyName = diagnosticListenerType.Assembly.GetName(); Log.Information("DiagnosticSource: {diagnosticSourceAssemblyNameFullName}", diagnosticSourceAssemblyName.FullName); var activityType = Type.GetType("System.Diagnostics.Activity, System.Diagnostics.DiagnosticSource", throwOnError: false); var version = diagnosticSourceAssemblyName.Version; // Check version: First version where the Activity objects has traceId and spanId if (version >= new Version(4, 0, 4)) { if (activityType is null) { Log.Error("The Activity type cannot be found."); return; } CreateCurrentActivityDelegates(activityType); ChangeActivityDefaultFormat(activityType); if (version.Major >= 5) { // if Version >= 5 loaded (Uses ActivityListener implementation) CreateActivityListenerInstance(activityType); } else { // if Version is 4.0.4 or greater (Uses DiagnosticListener implementation / Nuget version 4.6.0) CreateDiagnosticSourceListenerInstance(diagnosticListenerType); } return; } Log.Information("An activity listener was found but version {version} is not supported.", version?.ToString() ?? "(null)");
public CIWriterFileSender() { Log.Information("CIWriterFileSender Initialized."); }
internal async Task WriteDiagnosticLog() { string agentError = null; // In AAS, the trace agent is deployed alongside the tracer and managed by the tracer // Disable this check as it may hit the trace agent before it is ready to receive requests and give false negatives if (!AzureAppServices.Metadata.IsRelevant) { try { var success = await _agentWriter.Ping().ConfigureAwait(false); if (!success) { agentError = "An error occurred while sending traces to the agent"; } } catch (Exception ex) { agentError = ex.Message; } } try { var stringWriter = new StringWriter(); using (var writer = new JsonTextWriter(stringWriter)) { writer.WriteStartObject(); writer.WritePropertyName("date"); writer.WriteValue(DateTime.Now); writer.WritePropertyName("os_name"); writer.WriteValue(FrameworkDescription.Instance.OSPlatform); writer.WritePropertyName("os_version"); writer.WriteValue(Environment.OSVersion.ToString()); writer.WritePropertyName("version"); writer.WriteValue(TracerConstants.AssemblyVersion); writer.WritePropertyName("platform"); writer.WriteValue(FrameworkDescription.Instance.ProcessArchitecture); writer.WritePropertyName("lang"); writer.WriteValue(FrameworkDescription.Instance.Name); writer.WritePropertyName("lang_version"); writer.WriteValue(FrameworkDescription.Instance.ProductVersion); writer.WritePropertyName("env"); writer.WriteValue(Settings.Environment); writer.WritePropertyName("enabled"); writer.WriteValue(Settings.TraceEnabled); writer.WritePropertyName("service"); writer.WriteValue(DefaultServiceName); writer.WritePropertyName("agent_url"); writer.WriteValue(Settings.AgentUri); writer.WritePropertyName("debug"); writer.WriteValue(GlobalSettings.Source.DebugEnabled); writer.WritePropertyName("analytics_enabled"); writer.WriteValue(Settings.AnalyticsEnabled); writer.WritePropertyName("sample_rate"); writer.WriteValue(Settings.GlobalSamplingRate); writer.WritePropertyName("sampling_rules"); writer.WriteValue(Settings.CustomSamplingRules); writer.WritePropertyName("tags"); writer.WriteStartArray(); foreach (var entry in Settings.GlobalTags) { writer.WriteValue(string.Concat(entry.Key, ":", entry.Value)); } writer.WriteEndArray(); writer.WritePropertyName("log_injection_enabled"); writer.WriteValue(Settings.LogsInjectionEnabled); writer.WritePropertyName("runtime_metrics_enabled"); writer.WriteValue(Settings.RuntimeMetricsEnabled); writer.WritePropertyName("disabled_integrations"); writer.WriteStartArray(); foreach (var integration in Settings.DisabledIntegrationNames) { writer.WriteValue(integration); } writer.WriteEndArray(); writer.WritePropertyName("netstandard_enabled"); writer.WriteValue(Settings.IsNetStandardFeatureFlagEnabled()); writer.WritePropertyName("agent_reachable"); writer.WriteValue(agentError == null); writer.WritePropertyName("agent_error"); writer.WriteValue(agentError ?? string.Empty); writer.WriteEndObject(); } Log.Information("DATADOG TRACER CONFIGURATION - {Configuration}", stringWriter.ToString()); } catch (Exception ex) { Log.Warning(ex, "DATADOG TRACER DIAGNOSTICS - Error fetching configuration"); } }
/// <summary> /// Initializes global instrumentation values. /// </summary> public static void Initialize() { if (Interlocked.Exchange(ref _firstInitialization, 0) != 1) { // Initialize() was already called before return; } Log.Debug("Initialization started."); try { Log.Debug("Enabling by ref instrumentation."); NativeMethods.EnableByRefInstrumentation(); Log.Information("ByRef instrumentation enabled."); } catch (Exception ex) { Log.Error(ex, "ByRef instrumentation cannot be enabled: "); } try { Log.Debug("Enabling calltarget state by ref."); NativeMethods.EnableCallTargetStateByRef(); Log.Information("CallTarget State ByRef enabled."); } catch (Exception ex) { Log.Error(ex, "CallTarget state ByRef cannot be enabled: "); } try { Log.Debug("Sending CallTarget integration definitions to native library."); var payload = InstrumentationDefinitions.GetAllDefinitions(); NativeMethods.InitializeProfiler(payload.DefinitionsId, payload.Definitions); foreach (var def in payload.Definitions) { def.Dispose(); } Log.Information <int>("The profiler has been initialized with {count} definitions.", payload.Definitions.Length); } catch (Exception ex) { Log.Error(ex, ex.Message); } try { Serverless.InitIfNeeded(); } catch (Exception ex) { Serverless.Error("Error while loading Serverless definitions", ex); } try { Log.Debug("Sending CallTarget derived integration definitions to native library."); var payload = InstrumentationDefinitions.GetDerivedDefinitions(); NativeMethods.AddDerivedInstrumentations(payload.DefinitionsId, payload.Definitions); foreach (var def in payload.Definitions) { def.Dispose(); } Log.Information <int>("The profiler has been initialized with {count} derived definitions.", payload.Definitions.Length); } catch (Exception ex) { Log.Error(ex, ex.Message); } InitializeNoNativeParts(); Log.Debug("Initialization finished."); }
public ObfuscatorTraceProcessor(bool redisTagObfuscationEnabled) { _tagsProcessor = new(redisTagObfuscationEnabled); Log.Information("ObfuscatorTraceProcessor initialized. Redis tag obfuscation enabled: {RedisObfuscation}", redisTagObfuscationEnabled); }
public NormalizerTraceProcessor() { Log.Information("NormalizerTraceProcessor initialized."); }