From b7a3a834d02ae4c0cb904e43e35ce85d22017b77 Mon Sep 17 00:00:00 2001 From: Alan West <3676547+alanwest@users.noreply.github.com> Date: Fri, 24 Jun 2022 13:12:11 -0700 Subject: [PATCH] Handle possible exception when initializing the default service name (#3405) --- src/OpenTelemetry/CHANGELOG.md | 3 ++ .../Resources/ResourceBuilder.cs | 32 +++++++++++++++---- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/OpenTelemetry/CHANGELOG.md b/src/OpenTelemetry/CHANGELOG.md index 3b4cc4c70fe..bad0e536281 100644 --- a/src/OpenTelemetry/CHANGELOG.md +++ b/src/OpenTelemetry/CHANGELOG.md @@ -22,6 +22,9 @@ `set` methods ([#3378](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3378)) +* Handle possible exception when initializing the default service name. + ([#3405](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3405)) + ## 1.3.0 Released 2022-Jun-03 diff --git a/src/OpenTelemetry/Resources/ResourceBuilder.cs b/src/OpenTelemetry/Resources/ResourceBuilder.cs index c4c8ac15a6e..3abb89ea750 100644 --- a/src/OpenTelemetry/Resources/ResourceBuilder.cs +++ b/src/OpenTelemetry/Resources/ResourceBuilder.cs @@ -15,6 +15,7 @@ // using System.Collections.Generic; +using System.Diagnostics; using OpenTelemetry.Internal; namespace OpenTelemetry.Resources @@ -26,17 +27,34 @@ public class ResourceBuilder { private readonly List resources = new(); - private ResourceBuilder() + static ResourceBuilder() { + var defaultServiceName = "unknown_service"; + + try + { + var processName = Process.GetCurrentProcess().ProcessName; + if (!string.IsNullOrWhiteSpace(processName)) + { + defaultServiceName = $"{defaultServiceName}:{processName}"; + } + } + catch + { + // GetCurrentProcess can throw PlatformNotSupportedException + } + + DefaultResource = new Resource(new Dictionary + { + [ResourceSemanticConventions.AttributeServiceName] = defaultServiceName, + }); } - private static Resource DefaultResource { get; } = new Resource(new Dictionary + private ResourceBuilder() { - [ResourceSemanticConventions.AttributeServiceName] = "unknown_service" - + (string.IsNullOrWhiteSpace(System.Diagnostics.Process.GetCurrentProcess().ProcessName) - ? string.Empty : - ":" + System.Diagnostics.Process.GetCurrentProcess().ProcessName), - }); + } + + private static Resource DefaultResource { get; } /// /// Creates a instance with Default