Skip to content

Commit

Permalink
[sdk] Generate a consistent instanceId for the lifetime of a process (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
CodeBlanch authored Oct 25, 2023
1 parent c0a5577 commit cd8de07
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/OpenTelemetry/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
`8.0.0-rc.2.23479.6`.
([#4959](https://github.com/open-telemetry/opentelemetry-dotnet/pull/4959))

* The `AddService` `ResourceBuilder` extension method will now generate the same
`service.instance.id` for the lifetime of a process when
`autoGenerateServiceInstanceId` is `true`.
([#4988](https://github.com/open-telemetry/opentelemetry-dotnet/pull/4988))

## 1.7.0-alpha.1

Released 2023-Oct-16
Expand Down
4 changes: 3 additions & 1 deletion src/OpenTelemetry/Resources/ResourceBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ namespace OpenTelemetry.Resources;
/// </summary>
public static class ResourceBuilderExtensions
{
private static readonly string InstanceId = Guid.NewGuid().ToString();

private static Resource TelemetryResource { get; } = new Resource(new Dictionary<string, object>
{
[ResourceSemanticConventions.AttributeTelemetrySdkName] = "opentelemetry",
Expand Down Expand Up @@ -71,7 +73,7 @@ public static ResourceBuilder AddService(

if (serviceInstanceId == null && autoGenerateServiceInstanceId)
{
serviceInstanceId = Guid.NewGuid().ToString();
serviceInstanceId = InstanceId;
}

if (serviceInstanceId != null)
Expand Down
18 changes: 18 additions & 0 deletions test/OpenTelemetry.Tests/Resources/ResourceBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,24 @@ public void ServiceResource_AutoGenerateServiceInstanceIdOff()
Assert.Contains(new KeyValuePair<string, object>(ResourceSemanticConventions.AttributeServiceName, "my-service"), resource.Attributes);
}

[Fact]
public void ServiceResourceGeneratesConsistentInstanceId()
{
var firstResource = ResourceBuilder.CreateEmpty().AddService("my-service").Build();

var firstInstanceIdAttribute = firstResource.Attributes.FirstOrDefault(kvp => kvp.Key == ResourceSemanticConventions.AttributeServiceInstance);

Assert.NotNull(firstInstanceIdAttribute.Value);

var secondResource = ResourceBuilder.CreateEmpty().AddService("other-service").Build();

var secondInstanceIdAttribute = secondResource.Attributes.FirstOrDefault(kvp => kvp.Key == ResourceSemanticConventions.AttributeServiceInstance);

Assert.NotNull(secondInstanceIdAttribute.Value);

Assert.Equal(firstInstanceIdAttribute.Value, secondInstanceIdAttribute.Value);
}

[Fact]
public void ClearTest()
{
Expand Down

0 comments on commit cd8de07

Please sign in to comment.