|
| 1 | +// <copyright file="AzureFunctionsHostDetector.cs" company="Datadog"> |
| 2 | +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. |
| 3 | +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. |
| 4 | +// </copyright> |
| 5 | + |
| 6 | +using System; |
| 7 | +using System.Diagnostics; |
| 8 | +using System.Linq; |
| 9 | +using Datadog.Trace.Logging; |
| 10 | + |
| 11 | +internal static class AzureFunctionsHostDetector |
| 12 | +{ |
| 13 | + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(AzureFunctionsHostDetector)); |
| 14 | + |
| 15 | + public static readonly bool IsRunningInFunctionsHost; |
| 16 | + |
| 17 | + static AzureFunctionsHostDetector() |
| 18 | + { |
| 19 | + IsRunningInFunctionsHost = DetectIfFunctionsHost(); |
| 20 | + |
| 21 | + if (IsRunningInFunctionsHost) |
| 22 | + { |
| 23 | + Log.Information("Detected Azure Functions host process. Direct log submission will be disabled for ILogger to prevent duplicate logs."); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + private static bool DetectIfFunctionsHost() |
| 28 | + { |
| 29 | + try |
| 30 | + { |
| 31 | + var process = Process.GetCurrentProcess(); |
| 32 | + var processName = process.ProcessName.ToLowerInvariant(); |
| 33 | + |
| 34 | + // Check if we're in a known Azure Functions host process |
| 35 | + if (processName == "func" || |
| 36 | + processName.Contains("microsoft.azure.webjobs.script")) |
| 37 | + { |
| 38 | + var functionsRuntime = Environment.GetEnvironmentVariable("FUNCTIONS_WORKER_RUNTIME"); |
| 39 | + if (string.IsNullOrEmpty(functionsRuntime)) |
| 40 | + { |
| 41 | + return false; // Not Azure Functions |
| 42 | + } |
| 43 | + |
| 44 | + // The host process won't have this, but the worker will |
| 45 | + var workerId = Environment.GetEnvironmentVariable("FUNCTIONS_WORKER_ID"); |
| 46 | + if (!string.IsNullOrEmpty(workerId)) |
| 47 | + { |
| 48 | + // We're in the worker process, not the host |
| 49 | + return false; |
| 50 | + } |
| 51 | + |
| 52 | + // function host will have these loaded (I think) |
| 53 | + var hasHostAssemblies = AppDomain.CurrentDomain.GetAssemblies() |
| 54 | + .Any(a => a.GetName().Name == "Microsoft.Azure.WebJobs.Script.WebHost" || |
| 55 | + a.GetName().Name == "Microsoft.Azure.WebJobs.Script"); |
| 56 | + |
| 57 | + return hasHostAssemblies; |
| 58 | + } |
| 59 | + |
| 60 | + return false; |
| 61 | + } |
| 62 | + catch (Exception ex) |
| 63 | + { |
| 64 | + Log.Error(ex, "Error detecting Azure Functions host process"); |
| 65 | + return false; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments