Esempio n. 1
0
        public AzureAppServices(IDictionary environmentVariables)
        {
            try
            {
                IsRelevant = GetVariableIfExists(AzureAppServicesContextKey, environmentVariables)?.ToBoolean() ?? false;

                if (IsRelevant)
                {
                    var apiKey = GetVariableIfExists(Configuration.ConfigurationKeys.ApiKey, environmentVariables);
                    if (apiKey == null)
                    {
                        Log.Error("The Azure Site Extension will not work if you have not configured DD_API_KEY.");
                        IsUnsafeToTrace = true;
                        return;
                    }

                    // Azure App Services Basis
                    SubscriptionId = GetSubscriptionId(environmentVariables);
                    ResourceGroup  = GetVariableIfExists(ResourceGroupKey, environmentVariables);
                    SiteName       = GetVariableIfExists(SiteNameKey, environmentVariables);
                    ResourceId     = CompileResourceId();

                    InstanceId      = GetVariableIfExists(InstanceIdKey, environmentVariables);
                    InstanceName    = GetVariableIfExists(InstanceNameKey, environmentVariables);
                    OperatingSystem = GetVariableIfExists(OperatingSystemKey, environmentVariables);

                    // Functions
                    FunctionsWorkerRuntime =
                        GetVariableIfExists(
                            FunctionsWorkerRuntimeKey,
                            environmentVariables,
                            i => AzureContext = AzureContext.AzureFunction);
                    FunctionsExtensionVersion =
                        GetVariableIfExists(
                            FunctionsExtensionVersionKey,
                            environmentVariables,
                            i => AzureContext = AzureContext.AzureFunction);

                    switch (AzureContext)
                    {
                    case AzureContext.AzureFunction:
                        SiteKind = "functionapp";
                        SiteType = "function";
                        break;

                    case AzureContext.AzureAppService:
                        SiteKind = "app";
                        SiteType = "app";
                        break;
                    }

                    Runtime = FrameworkDescription.Instance.Name;
                }
            }
            catch (Exception ex)
            {
                IsUnsafeToTrace = true;
                Log.SafeLogError(ex, "Unable to initialize AzureAppServices metadata.");
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Gets an "application name" for the executing application by looking at
        /// the hosted app name (.NET Framework on IIS only), assembly name, and process name.
        /// </summary>
        /// <returns>The default service name.</returns>
        private static string GetApplicationName()
        {
            try
            {
                try
                {
                    if (TryLoadAspNetSiteName(out var siteName))
                    {
                        return(siteName);
                    }
                }
                catch (Exception ex)
                {
                    // Unable to call into System.Web.dll
                    Log.SafeLogError(ex, "Unable to get application name through ASP.NET settings");
                }

                return(Assembly.GetEntryAssembly()?.GetName().Name ??
                       ProcessHelpers.GetCurrentProcessName());
            }
            catch (Exception ex)
            {
                Log.SafeLogError(ex, "Error creating default service name.");
                return(null);
            }
        }
        private static string GetVersionFromAssemblyAttributes()
        {
            string productVersion = null;

            try
            {
                // if we fail to extract version from assembly path, fall back to the [AssemblyInformationalVersion],
                var informationalVersionAttribute = (AssemblyInformationalVersionAttribute)RootAssembly.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute));

                // split remove the commit hash from pre-release versions
                productVersion = informationalVersionAttribute?.InformationalVersion?.Split('+')[0];
            }
            catch (Exception e)
            {
                Log.SafeLogError(e, "Error getting framework version from [AssemblyInformationalVersion]");
            }

            if (productVersion == null)
            {
                try
                {
                    // and if that fails, try [AssemblyFileVersion]
                    var fileVersionAttribute = (AssemblyFileVersionAttribute)RootAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute));
                    productVersion = fileVersionAttribute?.Version;
                }
                catch (Exception e)
                {
                    Log.SafeLogError(e, "Error getting framework version from [AssemblyFileVersion]");
                }
            }

            return(productVersion);
        }
Esempio n. 4
0
        public AzureAppServices(IDictionary environmentVariables)
        {
            IsRelevant = GetVariableIfExists(AzureAppServicesContextKey, environmentVariables)?.ToBoolean() ?? false;
            if (IsRelevant)
            {
                // Azure App Services Basis
                SubscriptionId = GetSubscriptionId(environmentVariables);
                ResourceGroup  = GetVariableIfExists(ResourceGroupKey, environmentVariables);
                SiteName       = GetVariableIfExists(SiteNameKey, environmentVariables);
                ResourceId     = CompileResourceId();

                InstanceId      = GetVariableIfExists(InstanceIdKey, environmentVariables);
                InstanceName    = GetVariableIfExists(InstanceNameKey, environmentVariables);
                OperatingSystem = GetVariableIfExists(OperatingSystemKey, environmentVariables);

                // Functions
                FunctionsWorkerRuntime =
                    GetVariableIfExists(
                        FunctionsWorkerRuntimeKey,
                        environmentVariables,
                        i => AzureContext = AzureContext.AzureFunction);
                FunctionsExtensionVersion =
                    GetVariableIfExists(
                        FunctionsExtensionVersionKey,
                        environmentVariables,
                        i => AzureContext = AzureContext.AzureFunction);

                switch (AzureContext)
                {
                case AzureContext.AzureFunction:
                    SiteKind = "functionapp";
                    SiteType = "function";
                    break;

                case AzureContext.AzureAppService:
                    SiteKind = "app";
                    SiteType = "app";
                    break;
                }

                try
                {
                    var frameworkDescription = FrameworkDescription.Create();
                    Runtime = frameworkDescription.Name;
                }
                catch (Exception ex)
                {
                    Log.SafeLogError(ex, "Unable to determine runtime for Azure.");
                }
            }
        }
Esempio n. 5
0
        private async Task FlushTracesTaskLoopAsync()
        {
            while (true)
            {
                try
                {
                    await Task.WhenAny(Task.Delay(TimeSpan.FromSeconds(1)), _processExit.Task)
                    .ConfigureAwait(false);

                    if (_processExit.Task.IsCompleted)
                    {
                        await FlushTracesAsync().ConfigureAwait(false);

                        return;
                    }
                    else
                    {
                        await FlushTracesAsync().ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    Log.SafeLogError(ex, "An unhandled error occurred during the flushing task");
                }
            }
        }
        // IMPORTANT: For all logging frameworks, do not set any default values for
        //            "dd.trace_id" and "dd.span_id" when initializing the subscriber
        //            because the Tracer may be initialized at a time when it is not safe
        //            to add properties logging context of the underlying logging framework.
        //
        //            Failure to abide by this can cause a SerializationException when
        //            control is passed from one AppDomain to another where the originating
        //            AppDomain used a logging framework that stored logging context properties
        //            inside the System.Runtime.Remoting.Messaging.CallContext structure
        //            but the target AppDomain is unable to de-serialize the object --
        //            this can easily happen if the target AppDomain cannot find/load the
        //            logging framework assemblies.
        public LibLogScopeEventSubscriber(IScopeManager scopeManager, string defaultServiceName, string version, string env)
        {
            _scopeManager       = scopeManager;
            _defaultServiceName = defaultServiceName;
            _version            = version;
            _env = env;

            try
            {
                _logProvider = LogProvider.CurrentLogProvider ?? LogProvider.ResolveLogProvider();
                if (_logProvider is SerilogLogProvider)
                {
                    // Do not set default values for Serilog because it is unsafe to set
                    // except at the application startup, but this would require auto-instrumentation
                    _scopeManager.SpanOpened += StackOnSpanOpened;
                    _scopeManager.SpanClosed += StackOnSpanClosed;
                }
                else
                {
                    _scopeManager.SpanActivated += MapOnSpanActivated;
                    _scopeManager.TraceEnded    += MapOnTraceEnded;
                }
            }
            catch (Exception ex)
            {
                Log.SafeLogError(ex, "Could not successfully start the LibLogScopeEventSubscriber. There was an issue resolving the application logger.");
            }
        }
Esempio n. 7
0
        private static SpanContext ExtractPropagatedContext(HttpRequest request)
        {
            try
            {
                // extract propagation details from http headers
                var requestHeaders = request.Headers;

                if (requestHeaders != null)
                {
                    var headersCollection = new DictionaryHeadersCollection();

                    foreach (var header in requestHeaders)
                    {
                        string   key    = header.Key;
                        string[] values = header.Value.ToArray();

                        if (key != null && values.Length > 0)
                        {
                            headersCollection.Add(key, values);
                        }
                    }

                    return(SpanContextPropagator.Instance.Extract(headersCollection));
                }
            }
            catch (Exception ex)
            {
                Log.SafeLogError(ex, "Error extracting propagated HTTP headers.");
            }

            return(null);
        }
Esempio n. 8
0
 static DatadogLogger()
 {
     try
     {
         // Preload environment variables.
         CIEnvironmentValues.DecorateSpan(null);
     }
     catch (Exception ex)
     {
         Log.SafeLogError(ex, "Error initializing DatadogLogger type.");
     }
 }
        private static FrameworkDescription CreateFromRuntimeInformation()
        {
            string frameworkName = null;
            string osPlatform    = null;

            try
            {
                // RuntimeInformation.FrameworkDescription returns a string like ".NET Framework 4.7.2" or ".NET Core 2.1",
                // we want to return everything before the last space
                string frameworkDescription = RuntimeInformation.FrameworkDescription;
                int    index = frameworkDescription.LastIndexOf(' ');
                frameworkName = frameworkDescription.Substring(0, index).Trim();
            }
            catch (Exception e)
            {
                Log.SafeLogError(e, "Error getting framework name from RuntimeInformation");
            }

            if (RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
            {
                osPlatform = "Windows";
            }
            else if (RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux))
            {
                osPlatform = "Linux";
            }
            else if (RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX))
            {
                osPlatform = "MacOS";
            }

            return(new FrameworkDescription(
                       frameworkName ?? "unknown",
                       GetNetCoreVersion() ?? "unknown",
                       osPlatform ?? "unknown",
                       RuntimeInformation.OSArchitecture.ToString().ToLowerInvariant(),
                       RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant()));
        }
Esempio n. 10
0
        /// <summary>
        /// Gets an "application name" for the executing application by looking at
        /// the hosted app name (.NET Framework on IIS only), assembly name, and process name.
        /// </summary>
        /// <returns>The default service name.</returns>
        private static string GetApplicationName()
        {
            try
            {
#if NETFRAMEWORK
                // System.Web.dll is only available on .NET Framework
                if (System.Web.Hosting.HostingEnvironment.IsHosted)
                {
                    // if this app is an ASP.NET application, return "SiteName/ApplicationVirtualPath".
                    // note that ApplicationVirtualPath includes a leading slash.
                    return((System.Web.Hosting.HostingEnvironment.SiteName + System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath).TrimEnd('/'));
                }
#endif

                return(Assembly.GetEntryAssembly()?.GetName().Name ??
                       Process.GetCurrentProcess().ProcessName);
            }
            catch (Exception ex)
            {
                Log.SafeLogError(ex, "Error creating default service name.");
                return(null);
            }
        }
Esempio n. 11
0
 internal static void LogException(Exception exception)
 {
     Log.SafeLogError(exception, exception?.Message, null);
     if (exception is DuckTypeException)
     {
         Log.Warning($"DuckTypeException has been detected, the integration <{typeof(TIntegration)}, {typeof(TTarget)}> will be disabled.");
         _disableIntegration = true;
     }
     else if (exception is CallTargetInvokerException)
     {
         Log.Warning($"CallTargetInvokerException has been detected, the integration <{typeof(TIntegration)}, {typeof(TTarget)}> will be disabled.");
         _disableIntegration = true;
     }
 }
Esempio n. 12
0
        private string CompileResourceId()
        {
            string resourceId = null;

            try
            {
                var success = true;
                if (SubscriptionId == null)
                {
                    success = false;
                    Log.Warning("Could not successfully retrieve the subscription ID from variable: {0}", WebsiteOwnerNameKey);
                }

                if (SiteName == null)
                {
                    success = false;
                    Log.Warning("Could not successfully retrieve the deployment ID from variable: {0}", SiteNameKey);
                }

                if (ResourceGroup == null)
                {
                    success = false;
                    Log.Warning("Could not successfully retrieve the resource group name from variable: {0}", ResourceGroupKey);
                }

                if (success)
                {
                    resourceId = $"/subscriptions/{SubscriptionId}/resourcegroups/{ResourceGroup}/providers/microsoft.web/sites/{SiteName}".ToLowerInvariant();
                }
            }
            catch (Exception ex)
            {
                Log.SafeLogError(ex, "Could not successfully setup the resource id for azure app services.");
            }

            return(resourceId);
        }