Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for OTEL_SERVICE_NAME environmental variable #2209

Merged
merged 18 commits into from
Aug 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/OpenTelemetry/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## Unreleased

* `ResourceBuilder.AddEnvironmentVariableDetector` handles `OTEL_SERVICE_NAME`
environmental variable. ([#2209](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2209))

* Removes upper constraint for Microsoft.Extensions.Logging
dependencies. ([#2179](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2179))

Expand Down
20 changes: 16 additions & 4 deletions src/OpenTelemetry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@

* [Installation](#installation)
* [Introduction](#introduction)
* [Getting started with Logs](#getting-started-with-logging)
* [Getting started with Traces](#getting-started-with-tracing)
* [Tracing Configuration](#tracing-configuration)
* [ActivitySource](#activity-source)
* [Getting started with Logging](#getting-started-with-logging)
* [Getting started with Tracing](#getting-started-with-tracing)
* [Tracing configuration](#tracing-configuration)
* [Activity Source](#activity-source)
* [Instrumentation](#instrumentation)
* [Processor](#processor)
* [Resource](#resource)
* [Sampler](#sampler)
* [Advanced topics](#advanced-topics)
* [Propagators](#propagators)
* [Troubleshooting](#troubleshooting)
* [Configuration Parameters](#configuration-parameters)
* [Remarks](#remarks)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both Configuration Parameters and Remarks seem to be too detailed and generic for the ToC. Perhaps we want to remove the H3 (e.g. replace ### Remarks with **Remarks:**).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@open-telemetry/dotnet-maintainers WDYT - should I change it?

BTW I think that the Propagators section should be under Tracing configuration - and not under Advanced topics.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will make a separate PR for it as I did not get feedback on what is the preference

* [References](#references)

## Installation
Expand Down Expand Up @@ -243,6 +245,16 @@ using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.Build();
```

It is also possible to configure the `Resource` by using `AddEnvironmentVariableDetector`
together with following environmental variables:

<!-- markdownlint-disable MD013 -->
| Environment variable | Description |
| -------------------------- | -------------------------------------------------- |
| `OTEL_RESOURCE_ATTRIBUTES` | Key-value pairs to be used as resource attributes. See the [Resource SDK specification](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.5.0/specification/resource/sdk.md#specifying-resource-information-via-an-environment-variable) for more details. |
| `OTEL_SERVICE_NAME` | Sets the value of the `service.name` resource attribute. If `service.name` is also provided in `OTEL_RESOURCE_ATTRIBUTES`, then `OTEL_SERVICE_NAME` takes precedence. |
<!-- markdownlint-enable MD013 -->

### Sampler

[Samplers](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#sampler)
Expand Down
9 changes: 5 additions & 4 deletions src/OpenTelemetry/Resources/OtelEnvResourceDetector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@

using System;
using System.Collections.Generic;
using System.Security;
using OpenTelemetry.Internal;

namespace OpenTelemetry.Resources
{
internal class OtelEnvResourceDetector : IResourceDetector
{
private const string OTelResourceEnvVarKey = "OTEL_RESOURCE_ATTRIBUTES";
public const string EnvVarKey = "OTEL_RESOURCE_ATTRIBUTES";
private const char AttributeListSplitter = ',';
private const char AttributeKeyValueSplitter = '=';

Expand All @@ -32,16 +33,16 @@ public Resource Detect()

try
{
string envResourceAttributeValue = Environment.GetEnvironmentVariable(OTelResourceEnvVarKey);
string envResourceAttributeValue = Environment.GetEnvironmentVariable(EnvVarKey);
if (!string.IsNullOrEmpty(envResourceAttributeValue))
{
var attributes = ParseResourceAttributes(envResourceAttributeValue);
resource = new Resource(attributes);
}
}
catch (Exception ex)
catch (SecurityException ex)
{
OpenTelemetrySdkEventSource.Log.ResourceDetectorFailed("OtelEnvResourceDetector", ex.Message);
OpenTelemetrySdkEventSource.Log.ResourceDetectorFailed(nameof(OtelEnvResourceDetector), ex.Message);
pellared marked this conversation as resolved.
Show resolved Hide resolved
}

return resource;
Expand Down
51 changes: 51 additions & 0 deletions src/OpenTelemetry/Resources/OtelServiceNameEnvVarDetector.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// <copyright file="OtelServiceNameEnvVarDetector.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System;
using System.Collections.Generic;
using System.Security;
using OpenTelemetry.Internal;

namespace OpenTelemetry.Resources
{
internal class OtelServiceNameEnvVarDetector : IResourceDetector
{
public const string EnvVarKey = "OTEL_SERVICE_NAME";

public Resource Detect()
{
var resource = Resource.Empty;

try
{
string envResourceAttributeValue = Environment.GetEnvironmentVariable(EnvVarKey);
if (!string.IsNullOrEmpty(envResourceAttributeValue))
{
resource = new Resource(new Dictionary<string, object>
{
[ResourceSemanticConventions.AttributeServiceName] = envResourceAttributeValue,
});
}
}
catch (SecurityException ex)
{
OpenTelemetrySdkEventSource.Log.ResourceDetectorFailed(nameof(OtelServiceNameEnvVarDetector), ex.Message);
}

return resource;
}
}
}
6 changes: 3 additions & 3 deletions src/OpenTelemetry/Resources/ResourceBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,16 +110,16 @@ public static ResourceBuilder AddAttributes(this ResourceBuilder resourceBuilder
}

/// <summary>
/// Adds resource attributes parsed from an environment variable to a
/// <see cref="ResourceBuilder"/> following the <a
/// Adds resource attributes parsed from OTEL_RESOURCE_ATTRIBUTES, OTEL_SERVICE_NAME environment variables
/// to a <see cref="ResourceBuilder"/> following the <a
/// href="https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/sdk.md#specifying-resource-information-via-an-environment-variable">Resource
/// SDK</a>.
/// </summary>
/// <param name="resourceBuilder"><see cref="ResourceBuilder"/>.</param>
/// <returns>Returns <see cref="ResourceBuilder"/> for chaining.</returns>
public static ResourceBuilder AddEnvironmentVariableDetector(this ResourceBuilder resourceBuilder)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Couldn't this detector be out-of-the-box? This is what other languages do.

For sure something for a separate PR and maybe even needs some GH Issue for discussion.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 on making this out-of-the-box

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will make a separate PR to address it

{
return resourceBuilder.AddDetector(new OtelEnvResourceDetector());
return resourceBuilder.AddDetector(new OtelEnvResourceDetector()).AddDetector(new OtelServiceNameEnvVarDetector());
}

private static string GetFileVersion()
Expand Down
28 changes: 18 additions & 10 deletions test/OpenTelemetry.Tests/Resources/OtelEnvResourceDetectorTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,24 @@ namespace OpenTelemetry.Resources.Tests
{
public class OtelEnvResourceDetectorTest : IDisposable
{
private const string OtelEnvVarKey = "OTEL_RESOURCE_ATTRIBUTES";

public OtelEnvResourceDetectorTest()
{
Environment.SetEnvironmentVariable(OtelEnvVarKey, null);
Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, null);
}

public void Dispose()
{
Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, null);
}

[Fact]
public void OtelEnvResource_EnvVarKey()
{
// Act
var resource = new OtelServiceNameEnvVarDetector().Detect();

// Assert
Assert.Equal("OTEL_RESOURCE_ATTRIBUTES", OtelEnvResourceDetector.EnvVarKey);
}

[Fact]
Expand All @@ -44,7 +57,7 @@ public void OtelEnvResource_WithEnvVar_1()
{
// Arrange
var envVarValue = "Key1=Val1,Key2=Val2";
Environment.SetEnvironmentVariable(OtelEnvVarKey, envVarValue);
Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, envVarValue);
var resource = new OtelEnvResourceDetector().Detect();

// Assert
Expand All @@ -57,18 +70,13 @@ public void OtelEnvResource_WithEnvVar_2()
{
// Arrange
var envVarValue = "Key1,Key2=Val2";
Environment.SetEnvironmentVariable(OtelEnvVarKey, envVarValue);
Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, envVarValue);
var resource = new OtelEnvResourceDetector().Detect();

// Assert
Assert.NotEqual(Resource.Empty, resource);
Assert.Single(resource.Attributes);
Assert.Contains(new KeyValuePair<string, object>("Key2", "Val2"), resource.Attributes);
}

public void Dispose()
{
Environment.SetEnvironmentVariable(OtelEnvVarKey, null);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// <copyright file="OtelServiceNameEnvVarDetectorTests.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System;
using System.Collections.Generic;
using Xunit;

namespace OpenTelemetry.Resources.Tests
{
public class OtelServiceNameEnvVarDetectorTests : IDisposable
{
public OtelServiceNameEnvVarDetectorTests()
{
Environment.SetEnvironmentVariable(OtelServiceNameEnvVarDetector.EnvVarKey, null);
}

public void Dispose()
{
Environment.SetEnvironmentVariable(OtelServiceNameEnvVarDetector.EnvVarKey, null);
}

[Fact]
public void OtelServiceNameEnvVar_EnvVarKey()
{
// Act
var resource = new OtelServiceNameEnvVarDetector().Detect();

// Assert
Assert.Equal("OTEL_SERVICE_NAME", OtelServiceNameEnvVarDetector.EnvVarKey);
}

[Fact]
public void OtelServiceNameEnvVar_Null()
{
// Act
var resource = new OtelServiceNameEnvVarDetector().Detect();

// Assert
Assert.Equal(Resource.Empty, resource);
}

[Fact]
public void OtelServiceNameEnvVar_WithValue()
{
// Arrange
var envVarValue = "my-service";
Environment.SetEnvironmentVariable(OtelServiceNameEnvVarDetector.EnvVarKey, envVarValue);

// Act
var resource = new OtelServiceNameEnvVarDetector().Detect();

// Assert
Assert.NotEqual(Resource.Empty, resource);
Assert.Contains(new KeyValuePair<string, object>(ResourceSemanticConventions.AttributeServiceName, envVarValue), resource.Attributes);
}
}
}
63 changes: 56 additions & 7 deletions test/OpenTelemetry.Tests/Resources/ResourceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,19 @@ public class ResourceTest : IDisposable
{
private const string KeyName = "key";
private const string ValueName = "value";
private const string OtelEnvVarKey = "OTEL_RESOURCE_ATTRIBUTES";

public ResourceTest()
{
Environment.SetEnvironmentVariable(OtelEnvVarKey, null);
ClearEnvVars();
}

public void Dispose()
{
ClearEnvVars();
}

[Fact]
public static void CreateResource_NullAttributeCollection()
public void CreateResource_NullAttributeCollection()
{
// Act and Assert
var resource = new Resource(null);
Expand Down Expand Up @@ -421,10 +425,10 @@ public void GetResourceWithDefaultAttributes_ResourceWithAttrs()
}

[Fact]
public void GetResourceWithDefaultAttributes_WithEnvVar()
public void GetResourceWithDefaultAttributes_WithResourceEnvVar()
{
// Arrange
Environment.SetEnvironmentVariable(OtelEnvVarKey, "EVKey1=EVVal1,EVKey2=EVVal2");
Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, "EVKey1=EVVal1,EVKey2=EVVal2");
var resource = ResourceBuilder.CreateDefault().AddEnvironmentVariableDetector().AddAttributes(this.CreateAttributes(2)).Build();

// Assert
Expand All @@ -436,9 +440,54 @@ public void GetResourceWithDefaultAttributes_WithEnvVar()
Assert.Contains(new KeyValuePair<string, object>("EVKey2", "EVVal2"), attributes);
}

public void Dispose()
[Fact]
public void GetResource_WithServiceEnvVar()
{
// Arrange
Environment.SetEnvironmentVariable(OtelServiceNameEnvVarDetector.EnvVarKey, "some-service");
var resource = ResourceBuilder.CreateDefault().AddEnvironmentVariableDetector().AddAttributes(this.CreateAttributes(2)).Build();

// Assert
var attributes = resource.Attributes;
Assert.Equal(3, attributes.Count());
ValidateAttributes(attributes, 0, 1);
Assert.Contains(new KeyValuePair<string, object>("service.name", "some-service"), attributes);
}

[Fact]
public void GetResource_WithServiceNameSetWithTwoEnvVars()
{
// Arrange
Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, "service.name=from-resource-attr");
Environment.SetEnvironmentVariable(OtelServiceNameEnvVarDetector.EnvVarKey, "from-service-name");
var resource = ResourceBuilder.CreateDefault().AddEnvironmentVariableDetector().AddAttributes(this.CreateAttributes(2)).Build();

// Assert
var attributes = resource.Attributes;
Assert.Equal(3, attributes.Count());
ValidateAttributes(attributes, 0, 1);
Assert.Contains(new KeyValuePair<string, object>("service.name", "from-service-name"), attributes);
}

[Fact]
public void GetResource_WithServiceNameSetWithTwoEnvVarsAndCode()
{
// Arrange
Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, "service.name=from-resource-attr");
Environment.SetEnvironmentVariable(OtelServiceNameEnvVarDetector.EnvVarKey, "from-service-name");
var resource = ResourceBuilder.CreateDefault().AddEnvironmentVariableDetector().AddService("from-code").AddAttributes(this.CreateAttributes(2)).Build();

// Assert
var attributes = resource.Attributes;
Assert.Equal(4, attributes.Count());
ValidateAttributes(attributes, 0, 1);
Assert.Contains(new KeyValuePair<string, object>("service.name", "from-code"), attributes);
}

private static void ClearEnvVars()
{
Environment.SetEnvironmentVariable(OtelEnvVarKey, null);
Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, null);
Environment.SetEnvironmentVariable(OtelServiceNameEnvVarDetector.EnvVarKey, null);
}

private static void AddAttributes(Dictionary<string, object> attributes, int attributeCount, int startIndex = 0)
Expand Down