[logs-branch] Merge from main into main-logs (#3809)

* [Logs] Fix buffered log scopes being reused (#3731)

* Fix buffered log scopes being reused.

* CHANGELOG update.

* Test fixes.

Co-authored-by: Cijo Thomas <cithomas@microsoft.com>

* clarify that Prometheus HttpListner is not for production at this moment (#3737)

* [HttpClient] Export spans corresponding to retries (#3732)

* Minor update to OTLP readme (#3739)

* Nit fixes to prometheus readme

* Add minor clarification about OTLP logs

* Update workflow (#3741)

* Minor improvement to log message (#3742)

* [SDK + Jaeger] Support loading environment variables from IConfiguration in Traces & Metrics (#3720)

* Support retrieval of environment variables through IConfiguration in SDK.

* Update Jaeger to load environment variables through IConfiguration.

* Warning fix.

* CHANGELOG patch.

* Bug fixes.

* Warning cleanup.

* Code review.

* [Zipkin] Support loading envvars from IConfiguration (#3759)

* Support loading envvars from IConfiguration in Zipkin exporter.

* CHANGELOG patch.

* SqlClient Instrumentation to leverage native Activity Status. (#3751)

* [Metrics] Update default buckets for Explicit Bucket Histogram from spec (#3722)

* [Logs] Fix: Respect AttributeValueLengthLimit when building otlp LogRecord data (#3684)

* Respect SdkConfiguration.AttributeValueLengthLimit so otlp data points are not rejected by monitoring tools

* Respect maxAttributeCount and use OtlpKeyValueTransformer in AddStringAttribute and in AddIntAttribute

* Extend CHANGELOG.md

Co-authored-by: Mikel Blanchard <mblanchard@macrosssoftware.com>

* Bump actions/setup-dotnet from 3.0.1 to 3.0.2 (#3764)

Bumps [actions/setup-dotnet](https://github.com/actions/setup-dotnet) from 3.0.1 to 3.0.2.
- [Release notes](https://github.com/actions/setup-dotnet/releases)
- [Commits](https://github.com/actions/setup-dotnet/compare/v3.0.1...v3.0.2)

---
updated-dependencies:
- dependency-name: actions/setup-dotnet
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* [Repo] Attempting to stabilize the API Compatibility CI job (#3766)

* Attempting to stablize the API Compatibility CI.

* Tweak.

* More logging.

* Increase build logging level for api compat ci job.

* Tweak.

* Tweak.

* Revert extra logging in ci job.

* Switched some logging back to debug.

* Adding MinMax to Histograms (#2735)

* Logging state during building of TracerProvider (#3746)

* [HttpClient] Add unit tests for `RecordException` case (#3761)

* Add a separate example project for Logs redaction (#3744)

* Update CHANGELOG for 1.4.0-beta.2 release (#3772)

* [SDK + Otlp] Support loading envvars from IConfiguration (#3760)

* Updated Otlp Trace & Metrics exporters to load envvars from IConfiguration.

* Patch CHANGELOGs.

* Fix up otlp log exporter for SdkOptions changes.

* Revert SdkOptions public api.

* Restore tests.

* Fix benchmarks.

* SdkLimitOptions IConfiguration test.

* OtlpExporterOptions IConfiguration test.

* MetricReaderOptions IConfiguration test.

* Bug fix.

* Nit.

* [SqlClient] Add support for Filter expression (#3743)

* [SDK, Jaeger, Zipkin, & Otlp] Support loading envvars for BatchExportActivityProcessorOptions from IConfiguration (#3776)

* Support loading envvars for ExportActivityProcessorOptions & BatchExportActivityProcessorOptions from IConfiguration.

* Update src/OpenTelemetry/CHANGELOG.md

Co-authored-by: Piotr Kiełkowicz <pkiekowicz@splunk.com>

* Patch CHANGELOG.

* Unit test.

Co-authored-by: Cijo Thomas <cithomas@microsoft.com>
Co-authored-by: Piotr Kiełkowicz <pkiekowicz@splunk.com>

* Remove Env from CI `DOTNET_MULTILEVEL_LOOKUP = 1` (#3779)

* Link to .NET docs about different ports (#3704)

* Update DS to rc2 (#3781)

* ConsoleLogExporter to output full exception (#3784)

* [ASP.NET Core] Add back netstandard2.0 and 2.1 targets (#3755)

* [HttpClient] Add back netstandard2.0 target (#3787)

* Add back netstandard2.0 target

* changelog

* public api files

* Bump System.Text.Json version due to CVE-2021-26701 (#3789)

* Auto-generated Semantic Conventions (#2069)

* [SDK] Support dependency injection in ResourceBuilder and load envvars from IConfiguration (#3782)

* Add Vishwesh as an Approver (#3783)

Co-authored-by: Cijo Thomas <cijo.thomas@gmail.com>

* Move more SDK docs to docs folder (#3794)

* [Prometheus AspNetCore] Support named options in pipeline extensions (#3780)

* Support named options in Prometheus AspNetCore pipeline extensions.

* Patch CHANGELOG.

Co-authored-by: Cijo Thomas <cijo.thomas@gmail.com>

* [Logs] UnitTest: LogRecord attribute limits (#3758)

* Unittest for LogRecord attribute limits

* Remove maxValueLength from LogRecordExtensions.AddIntAttribute.

Change requested from https://github.com/open-telemetry/opentelemetry-dotnet/pull/3684#discussion_r995164277

* Pr commits addressed

Co-authored-by: Mikel Blanchard <mblanchard@macrosssoftware.com>

* Add MinMax to console and doc additions (#3795)

* Mark private and internal classes as sealed (#3799)

Co-authored-by: Cijo Thomas <cijo.thomas@gmail.com>

* Move more docs to docs folder (#3801)

* [ASP.NET Core] Update enrich callbacks to use specific type. (#3749)

* [Http] Update enrich callbacks for http (#3792)

* [SDK] Support dependency injection in the GetDefaultResource API (#3798)

* Support dependency injection in the GetDefaultResource API.

* CHANGELOG patch.

* Test tweaks.

Co-authored-by: Cijo Thomas <cijo.thomas@gmail.com>

* Fix circular reference issue building up tracer provider. (#3803)

* [SDK] Add some missing nullable annotations (#3796)

* Added some missing nullable annotations in SDK.

* Handle null span names in SamplingParameters.

* Warning cleanup.

* Warning cleanup.

* Added link to issue in comment.

Co-authored-by: Alan West <3676547+alanwest@users.noreply.github.com>

* Guard.Range now uses invariant culture for error message (#3778)

Co-authored-by: Utkarsh Umesan Pillai <utpilla@microsoft.com>

* Fix circular reference issue building up meter provider. (#3806)

Co-authored-by: Utkarsh Umesan Pillai <utpilla@microsoft.com>

* Add missing end of code block backticks (#3807)

* More doc tweaks (#3805)

* More doc tweaks

* remove draft staatus

* Update grpc client enrich callbacks (#3804)

* Port refactor from main-logs branch. (#3808)

Co-authored-by: Cijo Thomas <cijo.thomas@gmail.com>

* Merge fixes.

* Merge fixes.

* Merge fix.

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Cijo Thomas <cithomas@microsoft.com>
Co-authored-by: Reiley Yang <reyang@microsoft.com>
Co-authored-by: Vishwesh Bankwar <vishweshbankwar@users.noreply.github.com>
Co-authored-by: Cijo Thomas <cijo.thomas@gmail.com>
Co-authored-by: Yun-Ting Lin <yunl@microsoft.com>
Co-authored-by: Sebastian Schoder Moreno <35150382+schoder-moreno@users.noreply.github.com>
Co-authored-by: Jonathan Wilhelm <Jonathan.wilhelm@sage.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Michael Maxwell <micmax@microsoft.com>
Co-authored-by: ggoel <gaurav.goel111@gmail.com>
Co-authored-by: Utkarsh Umesan Pillai <utpilla@microsoft.com>
Co-authored-by: Pavel Steinl <pavel.steinl@gmail.com>
Co-authored-by: Piotr Kiełkowicz <pkiekowicz@splunk.com>
Co-authored-by: aristotelos <arisvd@gmail.com>
Co-authored-by: Joao Grassi <joao@joaograssi.com>
Co-authored-by: Alan West <3676547+alanwest@users.noreply.github.com>
Co-authored-by: benhall_io <3179852+benbhall@users.noreply.github.com>
This commit is contained in:
Mikel Blanchard 2022-10-24 13:55:49 -07:00 committed by GitHub
parent 4defde921a
commit aba8a6980d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
248 changed files with 8107 additions and 1405 deletions

View File

@ -11,13 +11,12 @@ jobs:
runs-on: windows-latest
env:
CheckAPICompatibility: true
# https://github.com/actions/setup-dotnet/issues/122
DOTNET_MULTILEVEL_LOOKUP: 1
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # fetching all
- uses: actions/setup-dotnet@v3.0.1
- uses: actions/setup-dotnet@v3.0.2
with:
dotnet-version: '7.0.x'
include-prerelease: true

View File

@ -18,16 +18,12 @@ jobs:
fail-fast: false
matrix:
os: [windows-latest]
env:
OS: ${{ matrix.os }}
# https://github.com/actions/setup-dotnet/issues/122
DOTNET_MULTILEVEL_LOOKUP: 1
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # fetching all
- uses: actions/setup-dotnet@v3.0.1
- uses: actions/setup-dotnet@v3.0.2
with:
dotnet-version: '7.0.x'
include-prerelease: true

View File

@ -21,7 +21,7 @@ jobs:
uses: actions/checkout@v3
- name: Setup .NET Core 7.0
uses: actions/setup-dotnet@v3.0.1
uses: actions/setup-dotnet@v3.0.2
with:
dotnet-version: '7.0.x'
include-prerelease: true

View File

@ -23,11 +23,11 @@ jobs:
with:
fetch-depth: 0 # fetching all
- uses: actions/setup-dotnet@v3.0.1
- uses: actions/setup-dotnet@v3.0.2
with:
dotnet-version: '6.0.x'
- uses: actions/setup-dotnet@v3.0.1
- uses: actions/setup-dotnet@v3.0.2
with:
dotnet-version: '7.0.x'
include-prerelease: true

View File

@ -23,7 +23,7 @@ jobs:
fetch-depth: 0 # fetching all
ref: ${{ github.ref || 'main' }}
- uses: actions/setup-dotnet@v3.0.1
- uses: actions/setup-dotnet@v3.0.2
with:
dotnet-version: '7.0.x'
include-prerelease: true

View File

@ -19,7 +19,7 @@ jobs:
strategy:
matrix:
version: [net462,net6.0]
version: [net462,net6.0,net7.0]
steps:
- run: 'echo "No build required"'

View File

@ -13,9 +13,6 @@ on:
jobs:
build-test:
runs-on: windows-latest
env:
# https://github.com/actions/setup-dotnet/issues/122
DOTNET_MULTILEVEL_LOOKUP: 1
strategy:
matrix:
@ -26,7 +23,7 @@ jobs:
with:
fetch-depth: 0 # fetching all
- uses: actions/setup-dotnet@v3.0.1
- uses: actions/setup-dotnet@v3.0.2
with:
dotnet-version: '7.0.x'
include-prerelease: true

View File

@ -41,6 +41,7 @@
"tracestate",
"Tracestate",
"triager",
"typeparam",
"umesan",
"unencrypted",
"unvalidated",

View File

@ -4,6 +4,13 @@
<PackProjects Include="src\**\*.csproj" />
<!-- Windows specific projects -->
<PackProjects Remove="src\OpenTelemetry.Instrumentation.AspNet\OpenTelemetry.Instrumentation.AspNet.csproj" Condition="'$(OS)' != 'Windows_NT'" />
<!-- Not pack SemanticConventions project for now -->
<SolutionProjects Remove="src\OpenTelemetry.SemanticConventions\OpenTelemetry.SemanticConventions.csproj" />
<PackProjects Remove="src\OpenTelemetry.SemanticConventions\OpenTelemetry.SemanticConventions.csproj" Condition="'$(OS)' != 'Windows_NT'" />
</ItemGroup>
<Target Name="Build">

View File

@ -212,6 +212,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "source-generation", "docs\l
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "getting-started-prometheus-grafana", "docs\metrics\getting-started-prometheus-grafana\getting-started-prometheus-grafana.csproj", "{41B784AA-3301-4126-AF9F-1D59BD04B0BF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenTelemetry.SemanticConventions", "src\OpenTelemetry.SemanticConventions\OpenTelemetry.SemanticConventions.csproj", "{D4519DF6-CC72-4AC4-A851-E21383098D11}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "customizing-the-sdk", "docs\logs\customizing-the-sdk\customizing-the-sdk.csproj", "{6C7A1595-36D6-4229-BBB5-5A6B5791791D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenTelemetry.Extensions.Propagators", "src\OpenTelemetry.Extensions.Propagators\OpenTelemetry.Extensions.Propagators.csproj", "{E91B2E40-E428-43B3-8A43-09709F0E69E4}"
@ -244,6 +246,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenTelemetry.Extensions.Ev
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenTelemetry.Extensions.Serilog.Tests", "test\OpenTelemetry.Extensions.Serilog.Tests\OpenTelemetry.Extensions.Serilog.Tests.csproj", "{3B3C3571-6116-49D6-B28F-2A541E003577}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "redaction", "docs\logs\redaction\redaction.csproj", "{A2DF46DE-50D7-4887-8C9D-4BD79CA19FAA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -442,6 +446,10 @@ Global
{41B784AA-3301-4126-AF9F-1D59BD04B0BF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{41B784AA-3301-4126-AF9F-1D59BD04B0BF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{41B784AA-3301-4126-AF9F-1D59BD04B0BF}.Release|Any CPU.Build.0 = Release|Any CPU
{D4519DF6-CC72-4AC4-A851-E21383098D11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D4519DF6-CC72-4AC4-A851-E21383098D11}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4519DF6-CC72-4AC4-A851-E21383098D11}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D4519DF6-CC72-4AC4-A851-E21383098D11}.Release|Any CPU.Build.0 = Release|Any CPU
{6C7A1595-36D6-4229-BBB5-5A6B5791791D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6C7A1595-36D6-4229-BBB5-5A6B5791791D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6C7A1595-36D6-4229-BBB5-5A6B5791791D}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -506,6 +514,10 @@ Global
{3B3C3571-6116-49D6-B28F-2A541E003577}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3B3C3571-6116-49D6-B28F-2A541E003577}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3B3C3571-6116-49D6-B28F-2A541E003577}.Release|Any CPU.Build.0 = Release|Any CPU
{A2DF46DE-50D7-4887-8C9D-4BD79CA19FAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A2DF46DE-50D7-4887-8C9D-4BD79CA19FAA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A2DF46DE-50D7-4887-8C9D-4BD79CA19FAA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A2DF46DE-50D7-4887-8C9D-4BD79CA19FAA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -543,6 +555,7 @@ Global
{9A07D215-90AC-4BAF-BCDB-73D74FD3A5C5} = {3862190B-E2C5-418E-AFDC-DB281FB5C705}
{5FDAF679-DE5A-4C73-A49B-8ABCF2399229} = {77C7929A-2EED-4AA6-8705-B5C443C8AA0F}
{7642798D-12D4-403A-BB92-B6BEF67C9D4F} = {E359BB2B-9AEC-497D-B321-7DF2450C3B8E}
{A2DF46DE-50D7-4887-8C9D-4BD79CA19FAA} = {3862190B-E2C5-418E-AFDC-DB281FB5C705}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {55639B5C-0770-4A22-AB56-859604650521}

View File

@ -118,6 +118,7 @@ If you have trouble accessing the doc, please get in touch on
* [Reiley Yang](https://github.com/reyang), Microsoft
* [Robert Paj&#x105;k](https://github.com/pellared), Splunk
* [Vishwesh Bankwar](https://github.com/vishweshbankwar), Microsoft
[Emeritus
Maintainer/Approver/Triager](https://github.com/open-telemetry/community/blob/main/community-membership.md#emeritus-maintainerapprovertriager):

View File

@ -13,11 +13,17 @@
<ItemGroup Condition="'$(MinVerTagPrefix)' == 'core-' AND '$(CheckAPICompatibility)' == 'true'">
<PackageReference Include="Microsoft.DotNet.ApiCompat" Version="6.0.0-beta.21308.1" PrivateAssets="All" />
<ResolvedMatchingContract Include="..\LastMajorVersionBinaries\$(AssemblyName)\$(OTelPreviousStableVer)\lib\$(TargetFramework)\$(AssemblyName).dll" />
<ResolvedMatchingContract Include="$(RepoRoot)\build\LastMajorVersionBinaries\$(AssemblyName)\$(OTelPreviousStableVer)\lib\$(TargetFramework)\$(AssemblyName).dll" />
</ItemGroup>
<Target Name="PreBuild" BeforeTargets="PreBuildEvent" Condition="'$(MinVerTagPrefix)' == 'core-' AND '$(CheckAPICompatibility)' == 'true'">
<Exec Command="powershell -ExecutionPolicy Unrestricted -File &quot;$(RepoRoot)\build\PreBuild.ps1&quot; -package $(AssemblyName) -version &quot;$(OTelPreviousStableVer)&quot;" />
<Target Name="PreBuild" BeforeTargets="DispatchToInnerBuilds;ValidateApiCompatForSrc" Condition="'$(MinVerTagPrefix)' == 'core-' AND '$(CheckAPICompatibility)' == 'true'">
<!-- Note: DispatchToInnerBuilds is called for projects with multiple
targets defined to spawn a build process for each target framework being
compiled. Executing BEFORE that step means this runs once for a project
instead of in parallel for each target framework defined. If we ever have a
project with only a single target, this will NOT run and an alternative
solution will be needed. -->
<Exec Command="powershell -ExecutionPolicy Unrestricted -File &quot;$(RepoRoot)\build\PreBuild.ps1&quot; -package $(AssemblyName) -version &quot;$(OTelPreviousStableVer)&quot; -workDir &quot;$(RepoRoot)\build\LastMajorVersionBinaries&quot;" />
</Target>
<Target Name="FindContractDependencyPaths" BeforeTargets="ValidateApiCompatForSrc" AfterTargets="ResolveAssemblyReferences" Condition="'$(MinVerTagPrefix)' == 'core-' AND '$(CheckAPICompatibility)' == 'true'">

View File

@ -31,10 +31,11 @@
<MicrosoftAspNetCoreHttpFeaturesPkgVer>[2.1.1,6.0)</MicrosoftAspNetCoreHttpFeaturesPkgVer>
<MicrosoftCodeAnalysisAnalyzersPkgVer>[3.3.3]</MicrosoftCodeAnalysisAnalyzersPkgVer>
<MicrosoftCodeCoveragePkgVer>[17.3.0]</MicrosoftCodeCoveragePkgVer>
<MicrosoftExtensionsConfigurationEnvironmentVariablesPkgVer>[3.1.0,)</MicrosoftExtensionsConfigurationEnvironmentVariablesPkgVer>
<MicrosoftExtensionsHostingAbstractionsPkgVer>[2.1.0,)</MicrosoftExtensionsHostingAbstractionsPkgVer>
<MicrosoftExtensionsLoggingPkgVer>[3.1.0,)</MicrosoftExtensionsLoggingPkgVer>
<MicrosoftExtensionsLoggingConfigurationPkgVer>[3.1.0,)</MicrosoftExtensionsLoggingConfigurationPkgVer>
<MicrosoftExtensionsOptionsPkgVer>[3.1.0,)</MicrosoftExtensionsOptionsPkgVer>
<MicrosoftExtensionsOptionsPkgVer>[5.0.0,)</MicrosoftExtensionsOptionsPkgVer>
<MicrosoftNETFrameworkReferenceAssembliesPkgVer>[1.0.0,2.0)</MicrosoftNETFrameworkReferenceAssembliesPkgVer>
<MicrosoftSourceLinkGitHubPkgVer>[1.0.0,2.0)</MicrosoftSourceLinkGitHubPkgVer>
<OpenTracingPkgVer>[0.12.1,0.13)</OpenTracingPkgVer>
@ -42,10 +43,10 @@
<SerilogPkgVer>[2.8.0,3.0)</SerilogPkgVer>
<StyleCopAnalyzersPkgVer>[1.2.0-beta.435,2.0)</StyleCopAnalyzersPkgVer>
<SystemCollectionsImmutablePkgVer>1.4.0</SystemCollectionsImmutablePkgVer>
<SystemDiagnosticSourcePkgVer>7.0.0-rc.1.22426.10</SystemDiagnosticSourcePkgVer>
<SystemDiagnosticSourcePkgVer>7.0.0-rc.2.22472.3</SystemDiagnosticSourcePkgVer>
<SystemReflectionEmitLightweightPkgVer>4.7.0</SystemReflectionEmitLightweightPkgVer>
<SystemTextJsonPkgVer>4.7.0</SystemTextJsonPkgVer>
<SystemThreadingTasksExtensionsPkgVer>4.5.3</SystemThreadingTasksExtensionsPkgVer>
<SystemTextJsonPkgVer>4.7.2</SystemTextJsonPkgVer>
<SystemThreadingTasksExtensionsPkgVer>4.5.4</SystemThreadingTasksExtensionsPkgVer>
</PropertyGroup>
<ItemGroup>

View File

@ -1,26 +1,31 @@
param([string]$package, [string]$version)
param(
[string]$package,
[string]$version,
[string]$workDir = ".\LastMajorVersionBinaries"
)
$workDir = "..\LastMajorVersionBinaries"
if (-Not (Test-Path $workDir))
{
Write-Host "Working directory for previous package versions not found, creating..."
Write-Host "Working directory for compatibility check packages '$workDir' not found, creating..."
New-Item -Path $workDir -ItemType "directory" | Out-Null
}
if (Test-Path -Path "$workDir\$package.$version.zip")
{
Write-Debug "Previous package version already downloaded"
Write-Debug "Previous package $package@$version already downloaded for compatibility check"
}
else
{
Write-Host "Retrieving $package @$version for compatibility check"
Write-Host "Retrieving package $package@$version for compatibility check"
Invoke-WebRequest -Uri https://www.nuget.org/api/v2/package/$package/$version -Outfile "$workDir\$package.$version.zip"
}
if (Test-Path -Path "$workDir\$package\$version\lib")
{
Write-Debug "Previous package version already extracted"
Write-Debug "Previous package $package@$version already extracted to '$workDir\$package\$version\lib'"
}
else
{
Write-Host "Extracting package $package@$version from '$workDir\$package.$version.zip' to '$workDir\$package\$version' for compatibility check"
Expand-Archive -LiteralPath "$workDir\$package.$version.zip" -DestinationPath "$workDir\$package\$version" -Force
}

View File

@ -27,7 +27,6 @@ public class Program
{
using var loggerFactory = LoggerFactory.Create(builder => builder
.AddOpenTelemetry(options => options.IncludeScopes = true)
.AddProcessor(new MyRedactionProcessor())
.AddProcessor(new MyProcessor("ProcessorA"))
.AddProcessor(new MyProcessor("ProcessorB"))
.AddProcessor(new SimpleLogRecordExportProcessor(new MyExporter("ExporterX")))

View File

@ -0,0 +1,36 @@
// <copyright file="Program.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 Microsoft.Extensions.Logging;
using OpenTelemetry.Logs;
namespace Redaction;
public class Program
{
public static void Main()
{
using var loggerFactory = LoggerFactory.Create(builder => builder
.AddOpenTelemetry()
.AddProcessor(new MyRedactionProcessor())
.AddConsoleExporter());
var logger = loggerFactory.CreateLogger<Program>();
// message will be redacted by MyRedactionProcessor
logger.LogInformation("OpenTelemetry {sensitiveString}.", "<secret>");
}
}

View File

@ -0,0 +1,6 @@
# Redaction
This example shows how to redact sensitive information from Logs.
In this example, we attach a custom `Processor` called `MyRedactionProcessor`
which is responsible for replacing any instance of the word "&lt;secret&gt;"
with the value "newRedactedValueHere".

View File

@ -0,0 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="$(MicrosoftExtensionsLoggingPkgVer)" />
<ProjectReference Include="$(RepoRoot)\src\OpenTelemetry.Exporter.Console\OpenTelemetry.Exporter.Console.csproj" />
</ItemGroup>
</Project>

View File

@ -18,6 +18,7 @@ using System;
using System.Diagnostics.Metrics;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
namespace CustomizingTheSdk;
@ -29,6 +30,7 @@ public class Program
public static void Main()
{
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.ConfigureResource(res => res.AddService("example-service"))
.AddMeter(Meter1.Name)
.AddMeter(Meter2.Name)

View File

@ -235,8 +235,7 @@ with the metric are of interest to you.
#### Specify custom boundaries for Histogram
By default, the boundaries used for a Histogram are [`{ 0, 5, 10, 25, 50, 75,
100, 250, 500,
1000}`](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#explicit-bucket-histogram-aggregation).
100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000}`](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.14.0/specification/metrics/sdk.md#explicit-bucket-histogram-aggregation).
Views can be used to provide custom boundaries for a Histogram. The measurements
are then aggregated using the custom boundaries provided instead of the the
default boundaries. This requires the use of
@ -428,4 +427,37 @@ Refer to the individual exporter docs to learn how to use them:
### Resource
// TODO
[Resource](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/sdk.md)
is the immutable representation of the entity producing the telemetry. If no
`Resource` is explicitly configured, the
[default](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#semantic-attributes-with-sdk-provided-default-value)
is to use a resource indicating this
[Service](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service).
The `ConfigureResource` method on `MeterProviderBuilder` can be used to set a
configure the resource on the provider. When the provider is built, it
automatically builds the final `Resource` from the configured `ResourceBuilder`.
There can only be a single `Resource` associated with a
provider. It is not possible to change the resource builder *after* the provider
is built, by calling the `Build()` method on the `MeterProviderBuilder`.
`ResourceBuilder` offers various methods to construct resource comprising of
multiple attributes from various sources.
The snippet below shows configuring the `Resource` associated with the provider.
```csharp
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.ConfigureResource(r => r.AddService("MyServiceName"))
.Build();
```
It is also possible to configure the `Resource` by using following
environmental variables:
| 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. |

View File

@ -16,6 +16,7 @@
using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
namespace CustomizingTheSdk;
@ -36,7 +37,7 @@ public class Program
public static void Main()
{
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
var tracerProvider = Sdk.CreateTracerProviderBuilder()
// The following adds subscription to activities from Activity Source
// named "MyCompany.MyProduct.MyLibrary" only.
@ -45,6 +46,8 @@ public class Program
// The following adds subscription to activities from all Activity Sources
// whose name starts with "AbcCompany.XyzProduct.".
.AddSource("AbcCompany.XyzProduct.*")
.ConfigureResource(resourceBuilder => resourceBuilder.AddTelemetrySdk())
.ConfigureResource(r => r.AddService("MyServiceName"))
.AddConsoleExporter()
.Build();
@ -76,5 +79,7 @@ public class Program
activity?.SetTag("foo", 1);
activity?.SetTag("bar", "Hello, World!");
}
tracerProvider.Dispose();
}
}

View File

@ -1,7 +1,5 @@
# Customizing OpenTelemetry .NET SDK
**This doc is work-in-progress.**
## TracerProvider
As shown in the [getting-started](../getting-started/README.md) doc, a valid
@ -23,15 +21,21 @@ Once built, changes to its configuration is not allowed, with the exception of
adding more processors. In most cases, a single `TracerProvider` is created at
the application startup, and is disposed when application shuts down.
The snippet below shows how to build a basic `TracerProvider`. This will create
a provider with default configuration, and is not particularly useful. The
subsequent sections shows how to build a more useful provider.
The snippet below shows how to build a basic `TracerProvider` and dispose it at
the end of the application. This will create a provider with default
configuration, and is not particularly useful. The subsequent sections shows how
to build a more useful provider.
```csharp
using OpenTelemetry;
using OpenTelemetry.Trace;
using var tracerProvider = Sdk.CreateTracerProviderBuilder().Build();
var tracerProvider = Sdk.CreateTracerProviderBuilder().Build();
// ....
// Dispose at application shutdown
tracerProvider.Dispose()
```
In a typical application, a single `TracerProvider` is created at application
@ -67,7 +71,7 @@ leveraging the built-in Dependency Injection container as shown
`ActivitySource` denotes a
[`Tracer`](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#tracer),
which is used to start activities. The SDK follows an explicit opt-in model for
which is used to create activities. The SDK follows an explicit opt-in model for
listening to activity sources. i.e, by default, it listens to no sources. Every
activity source which produce telemetry must be explicitly added to the tracer
provider to start collecting traces from them.
@ -87,7 +91,7 @@ The snippet below shows how to add activity sources to the provider.
using OpenTelemetry;
using OpenTelemetry.Trace;
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
var tracerProvider = Sdk.CreateTracerProviderBuilder()
// The following subscribes to activities from Activity Source
// named "MyCompany.MyProduct.MyLibrary" only.
.AddSource("MyCompany.MyProduct.MyLibrary")
@ -108,21 +112,175 @@ name starts with "Abc.".
### Instrumentation
// TODO
While the OpenTelemetry API can be used to instrument any library manually,
[Instrumentation
Libraries](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/overview.md#instrumentation-libraries)
are available for a lot of commonly used libraries. Such instrumentations can be
added to the `TracerProvider`. It is not required to attach the instrumentation
to the provider, unless the life cycle of the instrumentation must be managed by
the provider. If the instrumentation must be activated/shutdown/disposed along
with the provider, then the instrumentation must be added to the provider.
Typically, the instrumentation libraries provide extension methods on
`TracerProviderBuilder` to allow adding them to the `TracerProvider`. Please
refer to corresponding documentation of the instrumentation library to know the
exact method name.
Follow [this](../extending-the-sdk/README.md#instrumentation-library) document
to learn about the instrumentation libraries shipped from this repo.
### Processor
// TODO
[Processors](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#span-processor)
allows hooks for start and end of `Activity`. If no processors are configured,
then traces are simply dropped by the SDK. `AddProcessor` method on
`TracerProviderBuilder` should be used to add a processor. There can be any
number of processors added to the provider, and they are invoked in the same
order as they are added. Unlike `Sampler` or `Resource`, processors can be added
to the provider even *after* it is built.
The snippet below shows how to add processors to the provider before and after
it is built.
```csharp
using OpenTelemetry;
using OpenTelemetry.Trace;
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddProcessor(new MyProcessor1())
.AddProcessor(new MyProcessor2()))
.Build();
// Processors can be added to provider even after it is built.
// Only those traces which are emitted after this line, will be sent to it.
tracerProvider.AddProcessor(new MyProcessor3());
```
A `TracerProvider` assumes ownership of any processors added to it. This means
that, provider will call `Shutdown` method on the processor, when it is
shutdown, and disposes the processor when it is disposed. If multiple providers
are being setup in an application, then separate instances of processors must be
configured on them. Otherwise, shutting down one provider can cause the
processor in other provider to be shut down as well, leading to undesired
results.
Processors can be used for enriching the telemetry and exporting the telemetry
to an exporter. For enriching purposes, one must write a custom processor, and
override the `OnStart` or `OnEnd` method with logic to enrich the telemetry. For
exporting purposes, the SDK provides the following built-in processors:
* [BatchExportProcessor&lt;T&gt;](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#batching-processor)
: This is an exporting processor which batches the telemetry before sending to
the configured exporter.
The following environment variables can be used to override the default
values of the `BatchExportActivityProcessorOptions`.
| Environment variable | `BatchExportActivityProcessorOptions` property |
| -------------------------------- | ---------------------------------------------- |
| `OTEL_BSP_SCHEDULE_DELAY` | `ScheduledDelayMilliseconds` |
| `OTEL_BSP_EXPORT_TIMEOUT` | `ExporterTimeoutMilliseconds` |
| `OTEL_BSP_MAX_QUEUE_SIZE` | `MaxQueueSize` |
| `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` | `MaxExportBatchSizeEnvVarKey` |
`FormatException` is thrown in case of an invalid value for any of the
supported environment variables.
* [CompositeProcessor&lt;T&gt;](../../../src/OpenTelemetry/CompositeProcessor.cs)
: This is a processor which can be composed from multiple processors. This is
typically used to construct multiple processing pipelines, each ending with
its own exporter.
* [SimpleExportProcessor&lt;T&gt;](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#simple-processor)
: This is an exporting processor which passes telemetry to the configured
exporter without any batching.
Follow [this](../extending-the-sdk/README.md#processor) document
to learn about how to write own processors.
*The processors shipped from this SDK are generics, and supports tracing and
logging, by supporting `Activity` and `LogRecord` respectively.*
### Resource
// TODO
[Resource](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/sdk.md)
is the immutable representation of the entity producing the telemetry. If no
`Resource` is explicitly configured, the
[default](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#semantic-attributes-with-sdk-provided-default-value)
resource is used to indicate the
[Service](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service).
The `ConfigureResource` method on `TracerProviderBuilder` can be used to
configure the resource on the provider. `ConfigureResource` accepts an `Action`
to configure the `ResourceBuilder`. Multiple calls to `ConfigureResource` can be
made. When the provider is built, it builds the final `Resource` combining all
the `ConfigureResource` calls. There can only be a single `Resource` associated
with a provider. It is not possible to change the resource builder *after* the
provider is built, by calling the `Build()` method on the
`TracerProviderBuilder`.
`ResourceBuilder` offers various methods to construct resource comprising of
multiple attributes from various sources. Examples include `AddTelemetrySdk()`
which adds [Telemetry
Sdk](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#telemetry-sdk)
resource, and `AddService()` which adds
[Service](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service)
resource. It also allows adding `ResourceDetector`s.
Follow [this](../extending-the-sdk/README.md#resource-detector) document
to learn about how to write own resource detectors.
The snippet below shows configuring the `Resource` associated with the provider.
```csharp
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.ConfigureResource(resourceBuilder => resourceBuilder.AddTelemetrySdk())
.ConfigureResource(resourceBuilder => resourceBuilder.AddService("service-name"))
.Build();
```
It is also possible to configure the `Resource` by using following
environmental variables:
| 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. |
### Sampler
// TODO
[Samplers](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#sampler)
are used to control the noise and overhead introduced by OpenTelemetry by
reducing the number of samples of traces collected and sent to the processors.
If no sampler is explicitly configured, the default is to use
`ParentBased(root=AlwaysOn)`. `SetSampler` method on `TracerProviderBuilder` can
be used to set sampler. Only one sampler can be associated with a provider. If
multiple `SetSampler` is called, the last one wins. Also, it is not possible to
change the sampler *after* the provider is built, by calling the `Build()`
method on the `TracerProviderBuilder`.
The snippet below shows configuring a custom sampler to the provider.
```csharp
using OpenTelemetry;
using OpenTelemetry.Trace;
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.SetSampler(new TraceIdRatioBasedSampler(0.25))
.Build();
```
Follow [this](../extending-the-sdk/README.md#sampler) document
to learn about how to write own samplers.
## Context Propagation
// TODO: OpenTelemetry Sdk contents about Context. // TODO: Links to built-in
instrumentations doing Propagation.
## Configuration using Dependency Injection
// TODO: Placeholder

View File

@ -377,7 +377,7 @@ namespace OpenTelemetry
return baggageHolder;
}
private class BaggageHolder
private sealed class BaggageHolder
{
public Baggage Baggage;
}

View File

@ -7,6 +7,12 @@
## Unreleased
* Updated to System.Diagnostics.DiagnosticSource version `7.0.0-rc.2.22472.3`.
## 1.4.0-beta.2
Released 2022-Oct-17
## 1.4.0-beta.1
Released 2022-Sep-29

View File

@ -16,6 +16,7 @@
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading;
@ -198,7 +199,13 @@ namespace OpenTelemetry.Internal
{
var minMessage = minName != null ? $": {minName}" : string.Empty;
var maxMessage = maxName != null ? $": {maxName}" : string.Empty;
var exMessage = message ?? $"Must be in the range: [{min}{minMessage}, {max}{maxMessage}]";
var exMessage = message ?? string.Format(
CultureInfo.InvariantCulture,
"Must be in the range: [{0}{1}, {2}{3}]",
min,
minMessage,
max,
maxMessage);
throw new ArgumentOutOfRangeException(paramName, value, exMessage);
}
}

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.Internal
/// This is used for internal logging of this library.
/// </summary>
[EventSource(Name = "OpenTelemetry-Api")]
internal class OpenTelemetryApiEventSource : EventSource
internal sealed class OpenTelemetryApiEventSource : EventSource
{
public static OpenTelemetryApiEventSource Log = new();

View File

@ -9,6 +9,20 @@
## Unreleased
* Bumped the minimum required version of `System.Text.Json` to 4.7.2 in response
to [CVE-2021-26701](https://github.com/dotnet/runtime/issues/49377).
([#3789](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3789))
LogRecordExporter to print full exception details instead of just Message, when
using `ILogger` to log exception.
([#3784](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3784))
Added support to print Histogram Min, Max in MetricExporter.
## 1.4.0-beta.2
Released 2022-Oct-17
## 1.4.0-beta.1
Released 2022-Sep-29

View File

@ -16,6 +16,7 @@
using System;
using System.Collections.Generic;
using OpenTelemetry.Internal;
using OpenTelemetry.Logs;
using OpenTelemetry.Resources;
@ -125,7 +126,7 @@ namespace OpenTelemetry.Exporter
if (logRecord.Exception != null)
{
this.WriteLine($"{"LogRecord.Exception:",-RightPaddingLength}{logRecord.Exception?.Message}");
this.WriteLine($"{"LogRecord.Exception:",-RightPaddingLength}{logRecord.Exception.ToInvariantString()}");
}
int scopeDepth = -1;

View File

@ -97,7 +97,13 @@ namespace OpenTelemetry.Exporter
var bucketsBuilder = new StringBuilder();
var sum = metricPoint.GetHistogramSum();
var count = metricPoint.GetHistogramCount();
bucketsBuilder.Append($"Sum: {sum} Count: {count} \n");
bucketsBuilder.Append($"Sum: {sum} Count: {count} ");
if (metricPoint.HasMinMax())
{
bucketsBuilder.Append($"Min: {metricPoint.GetHistogramMin()} Max: {metricPoint.GetHistogramMax()} ");
}
bucketsBuilder.AppendLine();
bool isFirstIteration = true;
double previousExplicitBound = default;

View File

@ -21,7 +21,6 @@
</ItemGroup>
<ItemGroup>
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\EnvironmentVariableHelper.cs" Link="Includes\EnvironmentVariableHelper.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\OpenTelemetrySdkEventSource.cs" Link="Includes\OpenTelemetrySdkEventSource.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\PeriodicExportingMetricReaderHelper.cs" Link="Includes\PeriodicExportingMetricReaderHelper.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\TagTransformer.cs" Link="Includes\TagTransformer.cs" />

View File

@ -7,6 +7,10 @@
## Unreleased
## 1.4.0-beta.2
Released 2022-Oct-17
## 1.4.0-beta.1
Released 2022-Sep-29

View File

@ -1,4 +1,4 @@
// <auto-generated/> (Turns off StyleCop analysis in this file.)
// <auto-generated/> (Turns off StyleCop analysis in this file.)
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file

View File

@ -1,4 +1,4 @@
// <auto-generated/> (Turns off StyleCop analysis in this file.)
// <auto-generated/> (Turns off StyleCop analysis in this file.)
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file

View File

@ -2,6 +2,18 @@
## Unreleased
* Bumped the minimum required version of `System.Text.Json` to 4.7.2 in response
to [CVE-2021-26701](https://github.com/dotnet/runtime/issues/49377).
([#3789](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3789))
## 1.4.0-beta.2
Released 2022-Oct-17
* Added support for loading environment variables from `IConfiguration` when
using the `AddJaegerExporter` extension
([#3720](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3720))
## 1.4.0-beta.1
Released 2022-Sep-29

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.Exporter.Jaeger.Implementation
/// EventSource events emitted from the project.
/// </summary>
[EventSource(Name = "OpenTelemetry-Exporter-Jaeger")]
internal class JaegerExporterEventSource : EventSource
internal sealed class JaegerExporterEventSource : EventSource
{
public static JaegerExporterEventSource Log = new();

View File

@ -23,14 +23,9 @@ namespace OpenTelemetry.Exporter.Jaeger.Implementation
{
internal sealed class Process
{
public Process(string serviceName)
{
this.ServiceName = serviceName;
}
public string ServiceName { get; set; }
public string ServiceName { get; internal set; }
internal Dictionary<string, JaegerTag> Tags { get; set; }
public Dictionary<string, JaegerTag> Tags { get; set; }
public override string ToString()
{
@ -48,7 +43,7 @@ namespace OpenTelemetry.Exporter.Jaeger.Implementation
return sb.ToString();
}
internal void Write(TProtocol oprot)
public void Write(TProtocol oprot)
{
oprot.IncrementRecursionDepth();

View File

@ -78,14 +78,12 @@ namespace OpenTelemetry.Exporter
this.batchWriter = protocolFactory.GetProtocol(this.maxPayloadSizeInBytes * 2);
this.spanWriter = protocolFactory.GetProtocol(this.maxPayloadSizeInBytes);
string serviceName = (string)this.ParentProvider.GetDefaultResource().Attributes.FirstOrDefault(
pair => pair.Key == ResourceSemanticConventions.AttributeServiceName).Value;
this.Process = new Process(serviceName);
this.Process = new();
client.Connect();
}
internal Process Process { get; set; }
internal Process Process { get; }
internal EmitBatchArgs EmitBatchArgs { get; private set; }
@ -156,19 +154,21 @@ namespace OpenTelemetry.Exporter
}
}
if (serviceName != null)
if (!string.IsNullOrWhiteSpace(serviceName))
{
serviceName = string.IsNullOrEmpty(serviceNamespace)
? serviceName
: serviceNamespace + "." + serviceName;
}
if (!string.IsNullOrEmpty(serviceName))
else
{
process.ServiceName = serviceName;
serviceName = (string)this.ParentProvider.GetDefaultResource().Attributes.FirstOrDefault(
pair => pair.Key == ResourceSemanticConventions.AttributeServiceName).Value;
}
this.Batch = new Batch(this.Process, this.batchWriter);
process.ServiceName = serviceName;
this.Batch = new Batch(process, this.batchWriter);
if (this.sendUsingEmitBatchArgs)
{
this.EmitBatchArgs = new EmitBatchArgs(this.batchWriter);

View File

@ -62,10 +62,15 @@ namespace OpenTelemetry.Trace
name ??= Options.DefaultName;
if (configure != null)
builder.ConfigureServices(services =>
{
builder.ConfigureServices(services => services.Configure(name, configure));
}
if (configure != null)
{
services.Configure(name, configure);
}
services.RegisterOptionsFactory(configuration => new JaegerExporterOptions(configuration));
});
return builder.ConfigureBuilder((sp, builder) =>
{

View File

@ -17,6 +17,7 @@
using System;
using System.Diagnostics;
using System.Net.Http;
using Microsoft.Extensions.Configuration;
using OpenTelemetry.Internal;
using OpenTelemetry.Trace;
@ -43,37 +44,47 @@ namespace OpenTelemetry.Exporter
internal static readonly Func<HttpClient> DefaultHttpClientFactory = () => new HttpClient();
/// <summary>
/// Initializes a new instance of the <see cref="JaegerExporterOptions"/> class.
/// </summary>
public JaegerExporterOptions()
: this(new ConfigurationBuilder().AddEnvironmentVariables().Build())
{
if (EnvironmentVariableHelper.LoadString(OTelProtocolEnvVarKey, out string protocolEnvVar))
}
internal JaegerExporterOptions(IConfiguration configuration)
{
if (configuration.TryGetValue<JaegerExportProtocol>(
OTelProtocolEnvVarKey,
JaegerExporterProtocolParser.TryParse,
out var protocol))
{
if (JaegerExporterProtocolParser.TryParse(protocolEnvVar, out var protocol))
{
this.Protocol = protocol;
}
else
{
throw new FormatException($"{OTelProtocolEnvVarKey} environment variable has an invalid value: '{protocolEnvVar}'");
}
this.Protocol = protocol;
}
if (EnvironmentVariableHelper.LoadString(OTelAgentHostEnvVarKey, out string agentHostEnvVar))
if (configuration.TryGetStringValue(OTelAgentHostEnvVarKey, out var agentHost))
{
this.AgentHost = agentHostEnvVar;
this.AgentHost = agentHost;
}
if (EnvironmentVariableHelper.LoadNumeric(OTelAgentPortEnvVarKey, out int agentPortEnvVar))
if (configuration.TryGetIntValue(OTelAgentPortEnvVarKey, out var agentPort))
{
this.AgentPort = agentPortEnvVar;
this.AgentPort = agentPort;
}
if (EnvironmentVariableHelper.LoadString(OTelEndpointEnvVarKey, out string endpointEnvVar)
&& Uri.TryCreate(endpointEnvVar, UriKind.Absolute, out Uri endpoint))
if (configuration.TryGetUriValue(OTelEndpointEnvVarKey, out var endpoint))
{
this.Endpoint = endpoint;
}
this.BatchExportProcessorOptions = new BatchExportActivityProcessorOptions(configuration);
}
/// <summary>
/// Gets or sets the <see cref="JaegerExportProtocol"/> to use when
/// communicating to Jaeger. Default value: <see
/// cref="JaegerExportProtocol.UdpCompactThrift"/>.
/// </summary>
public JaegerExportProtocol Protocol { get; set; } = JaegerExportProtocol.UdpCompactThrift;
/// <summary>
@ -105,7 +116,7 @@ namespace OpenTelemetry.Exporter
/// <summary>
/// Gets or sets the BatchExportProcessor options. Ignored unless ExportProcessorType is BatchExporter.
/// </summary>
public BatchExportProcessorOptions<Activity> BatchExportProcessorOptions { get; set; } = new BatchExportActivityProcessorOptions();
public BatchExportProcessorOptions<Activity> BatchExportProcessorOptions { get; set; }
/// <summary>
/// Gets or sets the factory function called to create the <see

View File

@ -20,7 +20,7 @@ internal static class JaegerExporterProtocolParser
{
public static bool TryParse(string value, out JaegerExportProtocol result)
{
switch (value?.Trim())
switch (value.Trim().ToLower())
{
case "udp/thrift.compact":
result = JaegerExportProtocol.UdpCompactThrift;

View File

@ -19,7 +19,7 @@
<Compile Include="$(RepoRoot)\src\OpenTelemetry.Api\Internal\ActivityHelperExtensions.cs" Link="Includes\ActivityHelperExtensions.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry.Api\Internal\StatusHelper.cs" Link="Includes\StatusHelper.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry.Api\Internal\Guard.cs" Link="Includes\Guard.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\EnvironmentVariableHelper.cs" Link="Includes\EnvironmentVariableHelper.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\ConfigurationExtensions.cs" Link="Includes\ConfigurationExtensions.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\OpenTelemetrySdkEventSource.cs" Link="Includes\OpenTelemetrySdkEventSource.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\PooledList.cs" Link="Includes\PooledList.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\PeerServiceResolver.cs" Link="Includes\PeerServiceResolver.cs" />

View File

@ -9,6 +9,10 @@
## Unreleased
## 1.4.0-beta.2
Released 2022-Oct-17
## 1.4.0-beta.1
Released 2022-Sep-29

View File

@ -2,6 +2,24 @@
## Unreleased
## 1.4.0-beta.2
Released 2022-Oct-17
* OTLP histogram data points will now include `Min` and `Max` values when
they are present.
([#2735](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2735))
* Adds support for limiting the length and count of attributes exported from
the OTLP log exporter. These
[Attribute Limits](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/sdk-environment-variables.md#attribute-limits)
are configured via the environment variables defined in the specification.
([#3684](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3684))
* Added support for loading environment variables from `IConfiguration` when
using the `AddOtlpExporter` extensions
([#3760](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3760))
## 1.4.0-beta.1
Released 2022-Sep-29

View File

@ -1,46 +0,0 @@
// <copyright file="EnvironmentVariableConfiguration.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 OpenTelemetry.Internal;
namespace OpenTelemetry.Configuration;
internal class EnvironmentVariableConfiguration
{
public static void InitializeDefaultConfigurationFromEnvironment(SdkConfiguration sdkConfiguration)
{
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/sdk-environment-variables.md#attribute-limits
SetIntConfigValue("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT", value => sdkConfiguration.AttributeValueLengthLimit = value);
SetIntConfigValue("OTEL_ATTRIBUTE_COUNT_LIMIT", value => sdkConfiguration.AttributeCountLimit = value);
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/sdk-environment-variables.md#span-limits
SetIntConfigValue("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT", value => sdkConfiguration.SpanAttributeValueLengthLimit = value);
SetIntConfigValue("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", value => sdkConfiguration.SpanAttributeCountLimit = value);
SetIntConfigValue("OTEL_SPAN_EVENT_COUNT_LIMIT", value => sdkConfiguration.SpanEventCountLimit = value);
SetIntConfigValue("OTEL_SPAN_LINK_COUNT_LIMIT", value => sdkConfiguration.SpanLinkCountLimit = value);
SetIntConfigValue("OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT", value => sdkConfiguration.EventAttributeCountLimit = value);
SetIntConfigValue("OTEL_LINK_ATTRIBUTE_COUNT_LIMIT", value => sdkConfiguration.LinkAttributeCountLimit = value);
}
private static void SetIntConfigValue(string key, Action<int> setter)
{
if (EnvironmentVariableHelper.LoadNumeric(key, out var result))
{
setter(result);
}
}
}

View File

@ -1,69 +0,0 @@
// <copyright file="SdkConfiguration.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>
namespace OpenTelemetry.Configuration;
internal class SdkConfiguration
{
private int? spanAttributeValueLengthLimit;
private int? spanAttributeCountLimit;
private int? eventAttributeCountLimit;
private int? linkAttributeCountLimit;
private SdkConfiguration()
{
EnvironmentVariableConfiguration.InitializeDefaultConfigurationFromEnvironment(this);
}
public static SdkConfiguration Instance { get; private set; } = new SdkConfiguration();
public int? AttributeValueLengthLimit { get; set; }
public int? AttributeCountLimit { get; set; }
public int? SpanAttributeValueLengthLimit
{
get => this.spanAttributeValueLengthLimit ?? this.AttributeValueLengthLimit;
set => this.spanAttributeValueLengthLimit = value;
}
public int? SpanAttributeCountLimit
{
get => this.spanAttributeCountLimit ?? this.AttributeCountLimit;
set => this.spanAttributeCountLimit = value;
}
public int? SpanEventCountLimit { get; set; }
public int? SpanLinkCountLimit { get; set; }
public int? EventAttributeCountLimit
{
get => this.eventAttributeCountLimit ?? this.SpanAttributeCountLimit;
set => this.eventAttributeCountLimit = value;
}
public int? LinkAttributeCountLimit
{
get => this.linkAttributeCountLimit ?? this.SpanAttributeCountLimit;
set => this.linkAttributeCountLimit = value;
}
internal static void Reset()
{
Instance = new SdkConfiguration();
}
}

View File

@ -24,7 +24,6 @@ using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using Google.Protobuf;
using Google.Protobuf.Collections;
using OpenTelemetry.Configuration;
using OpenTelemetry.Internal;
using OpenTelemetry.Proto.Collector.Trace.V1;
using OpenTelemetry.Proto.Common.V1;
@ -42,6 +41,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
internal static void AddBatch(
this ExportTraceServiceRequest request,
SdkLimitOptions sdkLimitOptions,
Resource processResource,
in Batch<Activity> activityBatch)
{
@ -54,7 +54,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
foreach (var activity in activityBatch)
{
Span span = activity.ToOtlpSpan();
Span span = activity.ToOtlpSpan(sdkLimitOptions);
if (span == null)
{
OpenTelemetryProtocolExporterEventSource.Log.CouldNotTranslateActivity(
@ -116,7 +116,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Span ToOtlpSpan(this Activity activity)
internal static Span ToOtlpSpan(this Activity activity, SdkLimitOptions sdkLimitOptions)
{
if (activity.IdFormat != ActivityIdFormat.W3C)
{
@ -157,9 +157,10 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
TagEnumerationState otlpTags = new()
{
SdkLimitOptions = sdkLimitOptions,
Span = otlpSpan,
};
otlpTags.EnumerateTags(activity, SdkConfiguration.Instance.SpanAttributeCountLimit ?? int.MaxValue);
otlpTags.EnumerateTags(activity, sdkLimitOptions.SpanAttributeCountLimit ?? int.MaxValue);
if (activity.Kind == ActivityKind.Client || activity.Kind == ActivityKind.Producer)
{
@ -180,15 +181,17 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
EventEnumerationState otlpEvents = new()
{
SdkLimitOptions = sdkLimitOptions,
Span = otlpSpan,
};
otlpEvents.EnumerateEvents(activity, SdkConfiguration.Instance.SpanEventCountLimit ?? int.MaxValue);
otlpEvents.EnumerateEvents(activity, sdkLimitOptions.SpanEventCountLimit ?? int.MaxValue);
LinkEnumerationState otlpLinks = new()
{
SdkLimitOptions = sdkLimitOptions,
Span = otlpSpan,
};
otlpLinks.EnumerateLinks(activity, SdkConfiguration.Instance.SpanLinkCountLimit ?? int.MaxValue);
otlpLinks.EnumerateLinks(activity, sdkLimitOptions.SpanLinkCountLimit ?? int.MaxValue);
return otlpSpan;
}
@ -236,7 +239,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Span.Types.Link ToOtlpLink(in ActivityLink activityLink)
private static Span.Types.Link ToOtlpLink(in ActivityLink activityLink, SdkLimitOptions sdkLimitOptions)
{
byte[] traceIdBytes = new byte[16];
byte[] spanIdBytes = new byte[8];
@ -250,10 +253,10 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
SpanId = UnsafeByteOperations.UnsafeWrap(spanIdBytes),
};
int maxTags = SdkConfiguration.Instance.LinkAttributeCountLimit ?? int.MaxValue;
int maxTags = sdkLimitOptions.SpanLinkAttributeCountLimit ?? int.MaxValue;
foreach (ref readonly var tag in activityLink.EnumerateTagObjects())
{
if (OtlpKeyValueTransformer.Instance.TryTransformTag(tag, out var attribute, SdkConfiguration.Instance.AttributeValueLengthLimit))
if (OtlpKeyValueTransformer.Instance.TryTransformTag(tag, out var attribute, sdkLimitOptions.AttributeValueLengthLimit))
{
if (otlpLink.Attributes.Count < maxTags)
{
@ -270,7 +273,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Span.Types.Event ToOtlpEvent(in ActivityEvent activityEvent)
private static Span.Types.Event ToOtlpEvent(in ActivityEvent activityEvent, SdkLimitOptions sdkLimitOptions)
{
var otlpEvent = new Span.Types.Event
{
@ -278,10 +281,10 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
TimeUnixNano = (ulong)activityEvent.Timestamp.ToUnixTimeNanoseconds(),
};
int maxTags = SdkConfiguration.Instance.EventAttributeCountLimit ?? int.MaxValue;
int maxTags = sdkLimitOptions.SpanEventAttributeCountLimit ?? int.MaxValue;
foreach (ref readonly var tag in activityEvent.EnumerateTagObjects())
{
if (OtlpKeyValueTransformer.Instance.TryTransformTag(tag, out var attribute, SdkConfiguration.Instance.AttributeValueLengthLimit))
if (OtlpKeyValueTransformer.Instance.TryTransformTag(tag, out var attribute, sdkLimitOptions.AttributeValueLengthLimit))
{
if (otlpEvent.Attributes.Count < maxTags)
{
@ -320,6 +323,8 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
private struct TagEnumerationState : PeerServiceResolver.IPeerServiceState
{
public SdkLimitOptions SdkLimitOptions;
public Span Span;
public string StatusCode;
@ -357,7 +362,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
continue;
}
if (OtlpKeyValueTransformer.Instance.TryTransformTag(tag, out var attribute, SdkConfiguration.Instance.AttributeValueLengthLimit))
if (OtlpKeyValueTransformer.Instance.TryTransformTag(tag, out var attribute, this.SdkLimitOptions.AttributeValueLengthLimit))
{
if (this.Span.Attributes.Count < maxTags)
{
@ -384,6 +389,8 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
private struct EventEnumerationState
{
public SdkLimitOptions SdkLimitOptions;
public Span Span;
public void EnumerateEvents(Activity activity, int maxEvents)
@ -392,7 +399,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
{
if (this.Span.Events.Count < maxEvents)
{
this.Span.Events.Add(ToOtlpEvent(in @event));
this.Span.Events.Add(ToOtlpEvent(in @event, this.SdkLimitOptions));
}
else
{
@ -404,6 +411,8 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
private struct LinkEnumerationState
{
public SdkLimitOptions SdkLimitOptions;
public Span Span;
public void EnumerateLinks(Activity activity, int maxLinks)
@ -412,7 +421,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
{
if (this.Span.Links.Count < maxLinks)
{
this.Span.Links.Add(ToOtlpLink(in link));
this.Span.Links.Add(ToOtlpLink(in link, this.SdkLimitOptions));
}
else
{

View File

@ -18,7 +18,6 @@ using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Google.Protobuf;
using Google.Protobuf.Collections;
using OpenTelemetry.Internal;
using OpenTelemetry.Logs;
using OpenTelemetry.Trace;
@ -38,6 +37,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
internal static void AddBatch(
this OtlpCollector.ExportLogsServiceRequest request,
SdkLimitOptions sdkLimitOptions,
OtlpResource.Resource processResource,
in Batch<LogRecord> logRecordBatch)
{
@ -52,7 +52,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
foreach (var logRecord in logRecordBatch)
{
var otlpLogRecord = logRecord.ToOtlpLog();
var otlpLogRecord = logRecord.ToOtlpLog(sdkLimitOptions);
if (otlpLogRecord != null)
{
var instrumentationScope = logRecord.InstrumentationScope;
@ -105,7 +105,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static OtlpLogs.LogRecord ToOtlpLog(this LogRecord logRecord)
internal static OtlpLogs.LogRecord ToOtlpLog(this LogRecord logRecord, SdkLimitOptions sdkLimitOptions)
{
OtlpLogs.LogRecord otlpLogRecord = null;
@ -130,6 +130,11 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
}
}
var attributeValueLengthLimit = sdkLimitOptions.AttributeValueLengthLimit;
var attributeCountLimit = sdkLimitOptions.AttributeCountLimit ?? int.MaxValue;
// First add the generic attributes like category, eventid and exception, so they are less likely being dropped because of AttributeCountLimit
if (!string.IsNullOrEmpty(logRecord.CategoryName))
{
// TODO:
@ -137,7 +142,24 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
// if it makes it to log data model.
// https://github.com/open-telemetry/opentelemetry-specification/issues/2398
// 2. Confirm if this name for attribute is good.
otlpLogRecord.Attributes.AddStringAttribute("dotnet.ilogger.category", logRecord.CategoryName);
otlpLogRecord.AddStringAttribute("dotnet.ilogger.category", logRecord.CategoryName, attributeValueLengthLimit, attributeCountLimit);
}
if (logRecord.EventId.Id != default)
{
otlpLogRecord.AddIntAttribute(nameof(logRecord.EventId.Id), logRecord.EventId.Id, attributeCountLimit);
}
if (!string.IsNullOrEmpty(logRecord.EventId.Name))
{
otlpLogRecord.AddStringAttribute(nameof(logRecord.EventId.Name), logRecord.EventId.Name, attributeValueLengthLimit, attributeCountLimit);
}
if (logRecord.Exception != null)
{
otlpLogRecord.AddStringAttribute(SemanticConventions.AttributeExceptionType, logRecord.Exception.GetType().Name, attributeValueLengthLimit, attributeCountLimit);
otlpLogRecord.AddStringAttribute(SemanticConventions.AttributeExceptionMessage, logRecord.Exception.Message, attributeValueLengthLimit, attributeCountLimit);
otlpLogRecord.AddStringAttribute(SemanticConventions.AttributeExceptionStacktrace, logRecord.Exception.ToInvariantString(), attributeValueLengthLimit, attributeCountLimit);
}
bool bodyPopulatedFromFormattedMessage = false;
@ -158,30 +180,13 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
{
otlpLogRecord.Body = new OtlpCommon.AnyValue { StringValue = attribute.Value as string };
}
else if (OtlpKeyValueTransformer.Instance.TryTransformTag(attribute, out var result))
else if (OtlpKeyValueTransformer.Instance.TryTransformTag(attribute, out var result, attributeValueLengthLimit))
{
otlpLogRecord.Attributes.Add(result);
otlpLogRecord.AddAttribute(result, attributeCountLimit);
}
}
}
if (logRecord.EventId.Id != default)
{
otlpLogRecord.Attributes.AddIntAttribute(nameof(logRecord.EventId.Id), logRecord.EventId.Id);
}
if (!string.IsNullOrEmpty(logRecord.EventId.Name))
{
otlpLogRecord.Attributes.AddStringAttribute(nameof(logRecord.EventId.Name), logRecord.EventId.Name);
}
if (logRecord.Exception != null)
{
otlpLogRecord.Attributes.AddStringAttribute(SemanticConventions.AttributeExceptionType, logRecord.Exception.GetType().Name);
otlpLogRecord.Attributes.AddStringAttribute(SemanticConventions.AttributeExceptionMessage, logRecord.Exception.Message);
otlpLogRecord.Attributes.AddStringAttribute(SemanticConventions.AttributeExceptionStacktrace, logRecord.Exception.ToInvariantString());
}
if (logRecord.TraceId != default && logRecord.SpanId != default)
{
byte[] traceIdBytes = new byte[16];
@ -204,9 +209,9 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
foreach (var scopeItem in scope)
{
var scopeItemWithDepthInfo = new KeyValuePair<string, object>($"[Scope.{scopeDepth}]:{scopeItem.Key}", scopeItem.Value);
if (OtlpKeyValueTransformer.Instance.TryTransformTag(scopeItemWithDepthInfo, out var result))
if (OtlpKeyValueTransformer.Instance.TryTransformTag(scopeItemWithDepthInfo, out var result, attributeValueLengthLimit))
{
otlpLog.Attributes.Add(result);
otlpLog.AddAttribute(result, attributeCountLimit);
}
}
}
@ -219,22 +224,37 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
return otlpLogRecord;
}
private static void AddStringAttribute(this RepeatedField<OtlpCommon.KeyValue> repeatedField, string key, string value)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void AddAttribute(this OtlpLogs.LogRecord logRecord, OtlpCommon.KeyValue attribute, int maxAttributeCount)
{
repeatedField.Add(new OtlpCommon.KeyValue
if (logRecord.Attributes.Count < maxAttributeCount)
{
Key = key,
Value = new OtlpCommon.AnyValue { StringValue = value },
});
logRecord.Attributes.Add(attribute);
}
else
{
logRecord.DroppedAttributesCount++;
}
}
private static void AddIntAttribute(this RepeatedField<OtlpCommon.KeyValue> repeatedField, string key, int value)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void AddStringAttribute(this OtlpLogs.LogRecord logRecord, string key, string value, int? maxValueLength, int maxAttributeCount)
{
repeatedField.Add(new OtlpCommon.KeyValue
var attributeItem = new KeyValuePair<string, object>(key, value);
if (OtlpKeyValueTransformer.Instance.TryTransformTag(attributeItem, out var result, maxValueLength))
{
Key = key,
Value = new OtlpCommon.AnyValue { IntValue = value },
});
logRecord.AddAttribute(result, maxAttributeCount);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void AddIntAttribute(this OtlpLogs.LogRecord logRecord, string key, int value, int maxAttributeCount)
{
var attributeItem = new KeyValuePair<string, object>(key, value);
if (OtlpKeyValueTransformer.Instance.TryTransformTag(attributeItem, out var result))
{
logRecord.AddAttribute(result, maxAttributeCount);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]

View File

@ -257,6 +257,12 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
dataPoint.Count = (ulong)metricPoint.GetHistogramCount();
dataPoint.Sum = metricPoint.GetHistogramSum();
if (metricPoint.HasMinMax())
{
dataPoint.Min = metricPoint.GetHistogramMin();
dataPoint.Max = metricPoint.GetHistogramMax();
}
foreach (var histogramMeasurement in metricPoint.GetHistogramBuckets())
{
dataPoint.BucketCounts.Add((ulong)histogramMeasurement.BucketCount);

View File

@ -21,7 +21,7 @@ using OpenTelemetry.Internal;
namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
{
[EventSource(Name = "OpenTelemetry-Exporter-OpenTelemetryProtocol")]
internal class OpenTelemetryProtocolExporterEventSource : EventSource
internal sealed class OpenTelemetryProtocolExporterEventSource : EventSource
{
public static readonly OpenTelemetryProtocolExporterEventSource Log = new();

View File

@ -0,0 +1,125 @@
// <copyright file="SdkLimitOptions.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 Microsoft.Extensions.Configuration;
using OpenTelemetry.Internal;
namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation;
internal sealed class SdkLimitOptions
{
private int? spanAttributeValueLengthLimit;
private int? spanAttributeCountLimit;
private int? spanEventAttributeCountLimit;
private int? spanLinkAttributeCountLimit;
internal SdkLimitOptions()
: this(new ConfigurationBuilder().AddEnvironmentVariables().Build())
{
}
internal SdkLimitOptions(IConfiguration configuration)
{
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/sdk-environment-variables.md#attribute-limits
SetIntConfigValue(configuration, "OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT", value => this.AttributeValueLengthLimit = value);
SetIntConfigValue(configuration, "OTEL_ATTRIBUTE_COUNT_LIMIT", value => this.AttributeCountLimit = value);
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/sdk-environment-variables.md#span-limits
SetIntConfigValue(configuration, "OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT", value => this.SpanAttributeValueLengthLimit = value);
SetIntConfigValue(configuration, "OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", value => this.SpanAttributeCountLimit = value);
SetIntConfigValue(configuration, "OTEL_SPAN_EVENT_COUNT_LIMIT", value => this.SpanEventCountLimit = value);
SetIntConfigValue(configuration, "OTEL_SPAN_LINK_COUNT_LIMIT", value => this.SpanLinkCountLimit = value);
SetIntConfigValue(configuration, "OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT", value => this.SpanEventAttributeCountLimit = value);
SetIntConfigValue(configuration, "OTEL_LINK_ATTRIBUTE_COUNT_LIMIT", value => this.SpanLinkAttributeCountLimit = value);
}
/// <summary>
/// Gets or sets the maximum allowed attribute value size.
/// </summary>
public int? AttributeValueLengthLimit { get; set; }
/// <summary>
/// Gets or sets the maximum allowed attribute count.
/// </summary>
public int? AttributeCountLimit { get; set; }
/// <summary>
/// Gets or sets the maximum allowed span attribute value size.
/// </summary>
/// <remarks>
/// Note: Overrides the <see cref="AttributeValueLengthLimit"/> setting for spans if specified.
/// </remarks>
public int? SpanAttributeValueLengthLimit
{
get => this.spanAttributeValueLengthLimit ?? this.AttributeValueLengthLimit;
set => this.spanAttributeValueLengthLimit = value;
}
/// <summary>
/// Gets or sets the maximum allowed span attribute count.
/// </summary>
/// <remarks>
/// Note: Overrides the <see cref="AttributeCountLimit"/> setting for spans if specified.
/// </remarks>
public int? SpanAttributeCountLimit
{
get => this.spanAttributeCountLimit ?? this.AttributeCountLimit;
set => this.spanAttributeCountLimit = value;
}
/// <summary>
/// Gets or sets the maximum allowed span event count.
/// </summary>
public int? SpanEventCountLimit { get; set; }
/// <summary>
/// Gets or sets the maximum allowed span link count.
/// </summary>
public int? SpanLinkCountLimit { get; set; }
/// <summary>
/// Gets or sets the maximum allowed span event attribute count.
/// </summary>
/// <remarks>
/// Note: Overrides the <see cref="SpanAttributeCountLimit"/> setting for span events if specified.
/// </remarks>
public int? SpanEventAttributeCountLimit
{
get => this.spanEventAttributeCountLimit ?? this.SpanAttributeCountLimit;
set => this.spanEventAttributeCountLimit = value;
}
/// <summary>
/// Gets or sets the maximum allowed span link attribute count.
/// </summary>
/// <remarks>
/// Note: Overrides the <see cref="SpanAttributeCountLimit"/> setting for span links if specified.
/// </remarks>
public int? SpanLinkAttributeCountLimit
{
get => this.spanLinkAttributeCountLimit ?? this.SpanAttributeCountLimit;
set => this.spanLinkAttributeCountLimit = value;
}
private static void SetIntConfigValue(IConfiguration configuration, string key, Action<int> setter)
{
if (configuration.TryGetIntValue(key, out var result))
{
setter(result);
}
}
}

View File

@ -34,7 +34,7 @@
<Compile Include="$(RepoRoot)\src\OpenTelemetry.Api\Internal\ActivityHelperExtensions.cs" Link="Includes\ActivityHelperExtensions.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry.Api\Internal\StatusHelper.cs" Link="Includes\StatusHelper.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry.Api\Internal\Guard.cs" Link="Includes\Guard.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\EnvironmentVariableHelper.cs" Link="Includes\EnvironmentVariableHelper.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\ConfigurationExtensions.cs" Link="Includes\ConfigurationExtensions.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\OpenTelemetrySdkEventSource.cs" Link="Includes\OpenTelemetrySdkEventSource.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\PeriodicExportingMetricReaderHelper.cs" Link="Includes\PeriodicExportingMetricReaderHelper.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\PeerServiceResolver.cs" Link="Includes\PeerServiceResolver.cs" />

View File

@ -17,6 +17,7 @@
using System;
using System.Diagnostics;
using System.Net.Http;
using Microsoft.Extensions.Configuration;
using OpenTelemetry.Internal;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
@ -51,32 +52,33 @@ namespace OpenTelemetry.Exporter
/// Initializes a new instance of the <see cref="OtlpExporterOptions"/> class.
/// </summary>
public OtlpExporterOptions()
: this(new ConfigurationBuilder().AddEnvironmentVariables().Build())
{
if (EnvironmentVariableHelper.LoadUri(EndpointEnvVarName, out Uri parsedEndpoint))
}
internal OtlpExporterOptions(IConfiguration configuration)
{
if (configuration.TryGetUriValue(EndpointEnvVarName, out var endpoint))
{
this.endpoint = parsedEndpoint;
this.endpoint = endpoint;
}
if (EnvironmentVariableHelper.LoadString(HeadersEnvVarName, out string headersEnvVar))
if (configuration.TryGetStringValue(HeadersEnvVarName, out var headers))
{
this.Headers = headersEnvVar;
this.Headers = headers;
}
if (EnvironmentVariableHelper.LoadNumeric(TimeoutEnvVarName, out int timeout))
if (configuration.TryGetIntValue(TimeoutEnvVarName, out var timeout))
{
this.TimeoutMilliseconds = timeout;
}
if (EnvironmentVariableHelper.LoadString(ProtocolEnvVarName, out string protocolEnvVar))
if (configuration.TryGetValue<OtlpExportProtocol>(
ProtocolEnvVarName,
OtlpExportProtocolParser.TryParse,
out var protocol))
{
if (OtlpExportProtocolParser.TryParse(protocolEnvVar, out var protocol))
{
this.Protocol = protocol;
}
else
{
throw new FormatException($"{ProtocolEnvVarName} environment variable has an invalid value: '{protocolEnvVar}'");
}
this.Protocol = protocol;
}
this.HttpClientFactory = this.DefaultHttpClientFactory = () =>
@ -86,6 +88,8 @@ namespace OpenTelemetry.Exporter
Timeout = TimeSpan.FromMilliseconds(this.TimeoutMilliseconds),
};
};
this.BatchExportProcessorOptions = new BatchExportActivityProcessorOptions(configuration);
}
/// <summary>
@ -140,7 +144,7 @@ namespace OpenTelemetry.Exporter
/// <summary>
/// Gets or sets the BatchExportProcessor options. Ignored unless ExportProcessorType is Batch.
/// </summary>
public BatchExportProcessorOptions<Activity> BatchExportProcessorOptions { get; set; } = new BatchExportActivityProcessorOptions();
public BatchExportProcessorOptions<Activity> BatchExportProcessorOptions { get; set; }
/// <summary>
/// Gets or sets the factory function called to create the <see

View File

@ -15,6 +15,7 @@
// </copyright>
using System;
using System.Diagnostics;
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation;
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClient;
using OpenTelemetry.Logs;
@ -27,8 +28,9 @@ namespace OpenTelemetry.Exporter
/// Exporter consuming <see cref="LogRecord"/> and exporting the data using
/// the OpenTelemetry protocol (OTLP).
/// </summary>
internal class OtlpLogExporter : BaseExporter<LogRecord>
internal sealed class OtlpLogExporter : BaseExporter<LogRecord>
{
private readonly SdkLimitOptions sdkLimitOptions;
private readonly IExportClient<OtlpCollector.ExportLogsServiceRequest> exportClient;
private OtlpResource.Resource processResource;
@ -38,24 +40,33 @@ namespace OpenTelemetry.Exporter
/// </summary>
/// <param name="options">Configuration options for the exporter.</param>
public OtlpLogExporter(OtlpExporterOptions options)
: this(options, null)
: this(options, new(), null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OtlpLogExporter"/> class.
/// </summary>
/// <param name="options">Configuration options for the exporter.</param>
/// <param name="exporterOptions">Configuration options for the exporter.</param>
/// <param name="sdkLimitOptions"><see cref="SdkLimitOptions"/>.</param>
/// <param name="exportClient">Client used for sending export request.</param>
internal OtlpLogExporter(OtlpExporterOptions options, IExportClient<OtlpCollector.ExportLogsServiceRequest> exportClient = null)
internal OtlpLogExporter(
OtlpExporterOptions exporterOptions,
SdkLimitOptions sdkLimitOptions,
IExportClient<OtlpCollector.ExportLogsServiceRequest> exportClient = null)
{
Debug.Assert(exporterOptions != null, "exporterOptions was null");
Debug.Assert(sdkLimitOptions != null, "sdkLimitOptions was null");
this.sdkLimitOptions = sdkLimitOptions;
if (exportClient != null)
{
this.exportClient = exportClient;
}
else
{
this.exportClient = options.GetLogExportClient();
this.exportClient = exporterOptions.GetLogExportClient();
}
}
@ -71,7 +82,7 @@ namespace OpenTelemetry.Exporter
try
{
request.AddBatch(this.ProcessResource, logRecordBatch);
request.AddBatch(this.sdkLimitOptions, this.ProcessResource, logRecordBatch);
if (!this.exportClient.SendExportRequest(request))
{

View File

@ -60,10 +60,15 @@ namespace OpenTelemetry.Metrics
name ??= Options.DefaultName;
if (configureExporter != null)
builder.ConfigureServices(services =>
{
builder.ConfigureServices(services => services.Configure(name, configureExporter));
}
if (configureExporter != null)
{
services.Configure(name, configureExporter);
}
services.RegisterOptionsFactory(configuration => new OtlpExporterOptions(configuration));
});
return builder.ConfigureBuilder((sp, builder) =>
{
@ -106,6 +111,11 @@ namespace OpenTelemetry.Metrics
name ??= Options.DefaultName;
builder.ConfigureServices(services =>
{
services.RegisterOptionsFactory(configuration => new OtlpExporterOptions(configuration));
});
return builder.ConfigureBuilder((sp, builder) =>
{
var exporterOptions = sp.GetRequiredService<IOptionsMonitor<OtlpExporterOptions>>().Get(name);

View File

@ -29,6 +29,7 @@ namespace OpenTelemetry.Exporter
/// </summary>
public class OtlpTraceExporter : BaseExporter<Activity>
{
private readonly SdkLimitOptions sdkLimitOptions;
private readonly IExportClient<OtlpCollector.ExportTraceServiceRequest> exportClient;
private OtlpResource.Resource processResource;
@ -38,24 +39,33 @@ namespace OpenTelemetry.Exporter
/// </summary>
/// <param name="options">Configuration options for the export.</param>
public OtlpTraceExporter(OtlpExporterOptions options)
: this(options, null)
: this(options, new(), null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OtlpTraceExporter"/> class.
/// </summary>
/// <param name="options">Configuration options for the export.</param>
/// <param name="exporterOptions"><see cref="OtlpExporterOptions"/>.</param>
/// <param name="sdkLimitOptions"><see cref="SdkLimitOptions"/>.</param>
/// <param name="exportClient">Client used for sending export request.</param>
internal OtlpTraceExporter(OtlpExporterOptions options, IExportClient<OtlpCollector.ExportTraceServiceRequest> exportClient = null)
internal OtlpTraceExporter(
OtlpExporterOptions exporterOptions,
SdkLimitOptions sdkLimitOptions,
IExportClient<OtlpCollector.ExportTraceServiceRequest> exportClient = null)
{
Debug.Assert(exporterOptions != null, "exporterOptions was null");
Debug.Assert(sdkLimitOptions != null, "sdkLimitOptions was null");
this.sdkLimitOptions = sdkLimitOptions;
if (exportClient != null)
{
this.exportClient = exportClient;
}
else
{
this.exportClient = options.GetTraceExportClient();
this.exportClient = exporterOptions.GetTraceExportClient();
}
}
@ -71,7 +81,7 @@ namespace OpenTelemetry.Exporter
try
{
request.AddBatch(this.ProcessResource, activityBatch);
request.AddBatch(this.sdkLimitOptions, this.ProcessResource, activityBatch);
if (!this.exportClient.SendExportRequest(request))
{

View File

@ -19,6 +19,7 @@ using System.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OpenTelemetry.Exporter;
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation;
using OpenTelemetry.Internal;
namespace OpenTelemetry.Trace
@ -61,28 +62,40 @@ namespace OpenTelemetry.Trace
name ??= Options.DefaultName;
if (configure != null)
builder.ConfigureServices(services =>
{
builder.ConfigureServices(services => services.Configure(name, configure));
}
if (configure != null)
{
services.Configure(name, configure);
}
services.RegisterOptionsFactory(configuration => new SdkLimitOptions(configuration));
services.RegisterOptionsFactory(configuration => new OtlpExporterOptions(configuration));
});
return builder.ConfigureBuilder((sp, builder) =>
{
var options = sp.GetRequiredService<IOptionsMonitor<OtlpExporterOptions>>().Get(name);
var exporterOptions = sp.GetRequiredService<IOptionsMonitor<OtlpExporterOptions>>().Get(name);
AddOtlpExporter(builder, options, sp);
// Note: Not using name here for SdkLimitOptions. There should
// only be one provider for a given service collection so
// SdkLimitOptions is treated as a single default instance.
var sdkOptionsManager = sp.GetRequiredService<IOptionsMonitor<SdkLimitOptions>>().CurrentValue;
AddOtlpExporter(builder, exporterOptions, sdkOptionsManager, sp);
});
}
internal static TracerProviderBuilder AddOtlpExporter(
TracerProviderBuilder builder,
OtlpExporterOptions exporterOptions,
SdkLimitOptions sdkLimitOptions,
IServiceProvider serviceProvider,
Func<BaseExporter<Activity>, BaseExporter<Activity>> configureExporterInstance = null)
{
exporterOptions.TryEnableIHttpClientFactoryIntegration(serviceProvider, "OtlpTraceExporter");
BaseExporter<Activity> otlpExporter = new OtlpTraceExporter(exporterOptions);
BaseExporter<Activity> otlpExporter = new OtlpTraceExporter(exporterOptions, sdkLimitOptions);
if (configureExporterInstance != null)
{

View File

@ -77,14 +77,15 @@ supported environment variables.
## OTLP Logs
This package currently only supports exporting traces and metrics. Once the
[OTLP log data model](https://github.com/open-telemetry/opentelemetry-proto#maturity-level)
is deemed stable, the OTLP log exporter will be folded into this package.
In the meantime, support for exporting logs is provided by installing the
This package currently only supports exporting traces and metrics. Support for
exporting logs is provided by installing the
[`OpenTelemetry.Exporter.OpenTelemetryProtocol.Logs`](../OpenTelemetry.Exporter.OpenTelemetryProtocol.Logs/README.md)
package.
Once the OTLP log exporter is stable, it'll be folded into this package. Check
[this](https://github.com/open-telemetry/opentelemetry-dotnet/milestone/35)
milestone for tracking.
## Special case when using insecure channel
If your application is targeting .NET Core 3.1, and you are using an insecure

View File

@ -8,12 +8,12 @@ OpenTelemetry.Exporter.PrometheusAspNetCoreOptions.ScrapeResponseCacheDurationMi
OpenTelemetry.Exporter.PrometheusAspNetCoreOptions.ScrapeResponseCacheDurationMilliseconds.set -> void
OpenTelemetry.Metrics.PrometheusExporterMeterProviderBuilderExtensions
static Microsoft.AspNetCore.Builder.PrometheusExporterApplicationBuilderExtensions.UseOpenTelemetryPrometheusScrapingEndpoint(this Microsoft.AspNetCore.Builder.IApplicationBuilder app) -> Microsoft.AspNetCore.Builder.IApplicationBuilder
static Microsoft.AspNetCore.Builder.PrometheusExporterApplicationBuilderExtensions.UseOpenTelemetryPrometheusScrapingEndpoint(this Microsoft.AspNetCore.Builder.IApplicationBuilder app, OpenTelemetry.Metrics.MeterProvider meterProvider, System.Func<Microsoft.AspNetCore.Http.HttpContext, bool> predicate, string path, System.Action<Microsoft.AspNetCore.Builder.IApplicationBuilder> configureBranchedPipeline) -> Microsoft.AspNetCore.Builder.IApplicationBuilder
static Microsoft.AspNetCore.Builder.PrometheusExporterApplicationBuilderExtensions.UseOpenTelemetryPrometheusScrapingEndpoint(this Microsoft.AspNetCore.Builder.IApplicationBuilder app, OpenTelemetry.Metrics.MeterProvider meterProvider, System.Func<Microsoft.AspNetCore.Http.HttpContext, bool> predicate, string path, System.Action<Microsoft.AspNetCore.Builder.IApplicationBuilder> configureBranchedPipeline, string optionsName) -> Microsoft.AspNetCore.Builder.IApplicationBuilder
static Microsoft.AspNetCore.Builder.PrometheusExporterApplicationBuilderExtensions.UseOpenTelemetryPrometheusScrapingEndpoint(this Microsoft.AspNetCore.Builder.IApplicationBuilder app, string path) -> Microsoft.AspNetCore.Builder.IApplicationBuilder
static Microsoft.AspNetCore.Builder.PrometheusExporterApplicationBuilderExtensions.UseOpenTelemetryPrometheusScrapingEndpoint(this Microsoft.AspNetCore.Builder.IApplicationBuilder app, System.Func<Microsoft.AspNetCore.Http.HttpContext, bool> predicate) -> Microsoft.AspNetCore.Builder.IApplicationBuilder
static Microsoft.AspNetCore.Builder.PrometheusExporterEndpointRouteBuilderExtensions.MapPrometheusScrapingEndpoint(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder endpoints) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder
static Microsoft.AspNetCore.Builder.PrometheusExporterEndpointRouteBuilderExtensions.MapPrometheusScrapingEndpoint(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder endpoints, string path = null, OpenTelemetry.Metrics.MeterProvider meterProvider = null, System.Action<Microsoft.AspNetCore.Builder.IApplicationBuilder> configureBranchedPipeline = null) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder
static Microsoft.AspNetCore.Builder.PrometheusExporterEndpointRouteBuilderExtensions.MapPrometheusScrapingEndpoint(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder endpoints, string path) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder
static Microsoft.AspNetCore.Builder.PrometheusExporterEndpointRouteBuilderExtensions.MapPrometheusScrapingEndpoint(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder endpoints, string path, OpenTelemetry.Metrics.MeterProvider meterProvider, System.Action<Microsoft.AspNetCore.Builder.IApplicationBuilder> configureBranchedPipeline, string optionsName) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder
static OpenTelemetry.Metrics.PrometheusExporterMeterProviderBuilderExtensions.AddPrometheusExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder) -> OpenTelemetry.Metrics.MeterProviderBuilder
static OpenTelemetry.Metrics.PrometheusExporterMeterProviderBuilderExtensions.AddPrometheusExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, string name, System.Action<OpenTelemetry.Exporter.PrometheusAspNetCoreOptions> configure) -> OpenTelemetry.Metrics.MeterProviderBuilder
static OpenTelemetry.Metrics.PrometheusExporterMeterProviderBuilderExtensions.AddPrometheusExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action<OpenTelemetry.Exporter.PrometheusAspNetCoreOptions> configure) -> OpenTelemetry.Metrics.MeterProviderBuilder

View File

@ -2,6 +2,14 @@
## Unreleased
* Support named options in `UseOpenTelemetryPrometheusScrapingEndpoint` &
`MapPrometheusScrapingEndpoint` extensions
([#3780](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3780))
## 1.4.0-beta.2
Released 2022-Oct-17
* Changed configuration class name from `PrometheusExporterOptions`
to `PrometheusAspNetCoreOptions`
([#3717](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3717))

View File

@ -42,7 +42,7 @@ namespace Microsoft.AspNetCore.Builder
/// <returns>A reference to the original <see
/// cref="IApplicationBuilder"/> for chaining calls.</returns>
public static IApplicationBuilder UseOpenTelemetryPrometheusScrapingEndpoint(this IApplicationBuilder app)
=> UseOpenTelemetryPrometheusScrapingEndpoint(app, meterProvider: null, predicate: null, path: null, configureBranchedPipeline: null);
=> UseOpenTelemetryPrometheusScrapingEndpoint(app, meterProvider: null, predicate: null, path: null, configureBranchedPipeline: null, optionsName: null);
/// <summary>
/// Adds OpenTelemetry Prometheus scraping endpoint middleware to an
@ -58,7 +58,7 @@ namespace Microsoft.AspNetCore.Builder
public static IApplicationBuilder UseOpenTelemetryPrometheusScrapingEndpoint(this IApplicationBuilder app, string path)
{
Guard.ThrowIfNull(path);
return UseOpenTelemetryPrometheusScrapingEndpoint(app, meterProvider: null, predicate: null, path: path, configureBranchedPipeline: null);
return UseOpenTelemetryPrometheusScrapingEndpoint(app, meterProvider: null, predicate: null, path: path, configureBranchedPipeline: null, optionsName: null);
}
/// <summary>
@ -76,7 +76,7 @@ namespace Microsoft.AspNetCore.Builder
public static IApplicationBuilder UseOpenTelemetryPrometheusScrapingEndpoint(this IApplicationBuilder app, Func<HttpContext, bool> predicate)
{
Guard.ThrowIfNull(predicate);
return UseOpenTelemetryPrometheusScrapingEndpoint(app, meterProvider: null, predicate: predicate, path: null, configureBranchedPipeline: null);
return UseOpenTelemetryPrometheusScrapingEndpoint(app, meterProvider: null, predicate: predicate, path: null, configureBranchedPipeline: null, optionsName: null);
}
/// <summary>
@ -101,6 +101,8 @@ namespace Microsoft.AspNetCore.Builder
/// <param name="configureBranchedPipeline">Optional callback to
/// configure the branched pipeline. Called before registration of the
/// Prometheus middleware.</param>
/// <param name="optionsName">Optional name used to retrieve <see
/// cref="PrometheusAspNetCoreOptions"/>.</param>
/// <returns>A reference to the original <see
/// cref="IApplicationBuilder"/> for chaining calls.</returns>
public static IApplicationBuilder UseOpenTelemetryPrometheusScrapingEndpoint(
@ -108,7 +110,8 @@ namespace Microsoft.AspNetCore.Builder
MeterProvider meterProvider,
Func<HttpContext, bool> predicate,
string path,
Action<IApplicationBuilder> configureBranchedPipeline)
Action<IApplicationBuilder> configureBranchedPipeline,
string optionsName)
{
// Note: Order is important here. MeterProvider is accessed before
// GetOptions<PrometheusAspNetCoreOptions> so that any changes made to
@ -120,7 +123,7 @@ namespace Microsoft.AspNetCore.Builder
{
if (path == null)
{
var options = app.ApplicationServices.GetRequiredService<IOptions<PrometheusAspNetCoreOptions>>().Value;
var options = app.ApplicationServices.GetRequiredService<IOptionsMonitor<PrometheusAspNetCoreOptions>>().Get(optionsName ?? Options.DefaultName);
path = options.ScrapeEndpointPath ?? PrometheusAspNetCoreOptions.DefaultScrapeEndpointPath;
}

View File

@ -42,7 +42,7 @@ namespace Microsoft.AspNetCore.Builder
/// middleware to.</param>
/// <returns>A convention routes for the Prometheus scraping endpoint.</returns>
public static IEndpointConventionBuilder MapPrometheusScrapingEndpoint(this IEndpointRouteBuilder endpoints)
=> MapPrometheusScrapingEndpoint(endpoints, path: null, meterProvider: null, configureBranchedPipeline: null);
=> MapPrometheusScrapingEndpoint(endpoints, path: null, meterProvider: null, configureBranchedPipeline: null, optionsName: null);
/// <summary>
/// Adds OpenTelemetry Prometheus scraping endpoint middleware to an
@ -55,7 +55,7 @@ namespace Microsoft.AspNetCore.Builder
public static IEndpointConventionBuilder MapPrometheusScrapingEndpoint(this IEndpointRouteBuilder endpoints, string path)
{
Guard.ThrowIfNull(path);
return MapPrometheusScrapingEndpoint(endpoints, path, meterProvider: null, configureBranchedPipeline: null);
return MapPrometheusScrapingEndpoint(endpoints, path, meterProvider: null, configureBranchedPipeline: null, optionsName: null);
}
/// <summary>
@ -73,12 +73,15 @@ namespace Microsoft.AspNetCore.Builder
/// <param name="configureBranchedPipeline">Optional callback to
/// configure the branched pipeline. Called before registration of the
/// Prometheus middleware.</param>
/// <param name="optionsName">Optional name used to retrieve <see
/// cref="PrometheusAspNetCoreOptions"/>.</param>
/// <returns>A convention routes for the Prometheus scraping endpoint.</returns>
public static IEndpointConventionBuilder MapPrometheusScrapingEndpoint(
this IEndpointRouteBuilder endpoints,
string path = null,
MeterProvider meterProvider = null,
Action<IApplicationBuilder> configureBranchedPipeline = null)
string path,
MeterProvider meterProvider,
Action<IApplicationBuilder> configureBranchedPipeline,
string optionsName)
{
var builder = endpoints.CreateApplicationBuilder();
@ -90,7 +93,7 @@ namespace Microsoft.AspNetCore.Builder
if (path == null)
{
var options = endpoints.ServiceProvider.GetRequiredService<IOptions<PrometheusAspNetCoreOptions>>().Value;
var options = endpoints.ServiceProvider.GetRequiredService<IOptionsMonitor<PrometheusAspNetCoreOptions>>().Get(optionsName ?? Options.DefaultName);
path = options.ScrapeEndpointPath ?? PrometheusAspNetCoreOptions.DefaultScrapeEndpointPath;
}

View File

@ -66,6 +66,10 @@ dotnet add package --prerelease OpenTelemetry.Exporter.Prometheus.AspNetCore
&& context.Connection.LocalPort == 5067);
```
This can be used in combination with
[configuring multiple ports on the ASP.NET application](https://learn.microsoft.com/aspnet/core/fundamentals/servers/kestrel/endpoints)
to expose the scraping endpoint on a different port.
## Configuration
The `PrometheusExporter` can be configured using the `PrometheusAspNetCoreOptions`

View File

@ -2,6 +2,10 @@
## Unreleased
## 1.4.0-beta.2
Released 2022-Oct-17
## 1.4.0-beta.1
Released 2022-Sep-29

View File

@ -7,6 +7,14 @@ An [OpenTelemetry Prometheus exporter](https://github.com/open-telemetry/opentel
that configures an [HttpListener](https://docs.microsoft.com/dotnet/api/system.net.httplistener)
instance for Prometheus to scrape.
**Warning**: this component is intended for dev inner-loop, there is no plan to
make it production ready. Production environments should use
[OpenTelemetry.Exporter.Prometheus.AspNetCore](../OpenTelemetry.Exporter.Prometheus.AspNetCore/README.md),
or a combination of
[OpenTelemetry.Exporter.OpenTelemetryProtocol](../OpenTelemetry.Exporter.OpenTelemetryProtocol/README.md)
and [OpenTelemetry
Collector](https://github.com/open-telemetry/opentelemetry-collector).
## Prerequisite
* [Get Prometheus](https://prometheus.io/docs/introduction/first_steps/)

View File

@ -2,6 +2,10 @@
## Unreleased
## 1.0.0-rc9.8
Released 2022-Oct-17
## 1.0.0-rc9.7
Released 2022-Sep-29

View File

@ -22,7 +22,7 @@ namespace OpenTelemetry.Exporter.ZPages.Implementation
/// <summary>
/// Stores the activity information aggregated according to activity name.
/// </summary>
internal class ZPagesActivityAggregate
internal sealed class ZPagesActivityAggregate
{
/// <summary>
/// Initializes a new instance of the <see cref="ZPagesActivityAggregate"/> class.

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.Exporter.ZPages.Implementation
/// EventSource events emitted from the project.
/// </summary>
[EventSource(Name = "OpenTelemetry-Exporter-ZPages")]
internal class ZPagesExporterEventSource : EventSource
internal sealed class ZPagesExporterEventSource : EventSource
{
public static ZPagesExporterEventSource Log = new();

View File

@ -16,7 +16,7 @@
namespace OpenTelemetry.Exporter.ZPages.Implementation
{
internal class ZPagesStatsBuilder
internal sealed class ZPagesStatsBuilder
{
public const string ContentType = "text/html";
}

View File

@ -2,6 +2,18 @@
## Unreleased
* Bumped the minimum required version of `System.Text.Json` to 4.7.2 in response
to [CVE-2021-26701](https://github.com/dotnet/runtime/issues/49377).
([#3789](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3789))
## 1.4.0-beta.2
Released 2022-Oct-17
* Added support for loading environment variables from `IConfiguration` when
using the `AddZipkinExporter` extension
([#3759](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3759))
## 1.4.0-beta.1
Released 2022-Sep-29

View File

@ -19,7 +19,7 @@ using System.Text.Json;
namespace OpenTelemetry.Exporter.Zipkin.Implementation
{
internal class ZipkinEndpoint
internal sealed class ZipkinEndpoint
{
public ZipkinEndpoint(string serviceName)
: this(serviceName, null, null, null, null)

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.Exporter.Zipkin.Implementation
/// EventSource events emitted from the project.
/// </summary>
[EventSource(Name = "OpenTelemetry-Exporter-Zipkin")]
internal class ZipkinExporterEventSource : EventSource
internal sealed class ZipkinExporterEventSource : EventSource
{
public static ZipkinExporterEventSource Log = new();

View File

@ -14,7 +14,7 @@
<Compile Include="$(RepoRoot)\src\OpenTelemetry.Api\Internal\ActivityHelperExtensions.cs" Link="Includes\ActivityHelperExtensions.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry.Api\Internal\StatusHelper.cs" Link="Includes\StatusHelper.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry.Api\Internal\Guard.cs" Link="Includes\Guard.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\EnvironmentVariableHelper.cs" Link="Includes\EnvironmentVariableHelper.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\ConfigurationExtensions.cs" Link="Includes\ConfigurationExtensions.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\OpenTelemetrySdkEventSource.cs" Link="Includes\OpenTelemetrySdkEventSource.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\PooledList.cs" Link="Includes\PooledList.cs" />
<Compile Include="$(RepoRoot)\src\OpenTelemetry\Internal\PeerServiceResolver.cs" Link="Includes\PeerServiceResolver.cs" />

View File

@ -62,10 +62,15 @@ namespace OpenTelemetry.Trace
name ??= Options.DefaultName;
if (configure != null)
builder.ConfigureServices(services =>
{
builder.ConfigureServices(services => services.Configure(name, configure));
}
if (configure != null)
{
services.Configure(name, configure);
}
services.RegisterOptionsFactory(configuration => new ZipkinExporterOptions(configuration));
});
return builder.ConfigureBuilder((sp, builder) =>
{

View File

@ -17,6 +17,7 @@
using System;
using System.Diagnostics;
using System.Net.Http;
using Microsoft.Extensions.Configuration;
using OpenTelemetry.Internal;
using OpenTelemetry.Trace;
@ -44,11 +45,18 @@ namespace OpenTelemetry.Exporter
/// Initializes zipkin endpoint.
/// </summary>
public ZipkinExporterOptions()
: this(new ConfigurationBuilder().AddEnvironmentVariables().Build())
{
if (EnvironmentVariableHelper.LoadUri(ZipkinEndpointEnvVar, out Uri endpoint))
}
internal ZipkinExporterOptions(IConfiguration configuration)
{
if (configuration.TryGetUriValue(ZipkinEndpointEnvVar, out var endpoint))
{
this.Endpoint = endpoint;
}
this.BatchExportProcessorOptions = new BatchExportActivityProcessorOptions(configuration);
}
/// <summary>
@ -75,7 +83,7 @@ namespace OpenTelemetry.Exporter
/// <summary>
/// Gets or sets the BatchExportProcessor options. Ignored unless ExportProcessorType is BatchExporter.
/// </summary>
public BatchExportProcessorOptions<Activity> BatchExportProcessorOptions { get; set; } = new BatchExportActivityProcessorOptions();
public BatchExportProcessorOptions<Activity> BatchExportProcessorOptions { get; set; }
/// <summary>
/// Gets or sets the factory function called to create the <see

View File

@ -2,6 +2,10 @@
## Unreleased
## 1.0.0-rc9.8
Released 2022-Oct-17
## 1.0.0-rc9.7
Released 2022-Sep-29

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.Extensions.Hosting.Implementation
/// EventSource events emitted from the project.
/// </summary>
[EventSource(Name = "OpenTelemetry-Extensions-Hosting")]
internal class HostingExtensionsEventSource : EventSource
internal sealed class HostingExtensionsEventSource : EventSource
{
public static HostingExtensionsEventSource Log = new();

View File

@ -2,6 +2,10 @@
## Unreleased
## 1.4.0-beta.2
Released 2022-Oct-17
## 1.4.0-beta.1
Released 2022-Sep-29

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.Internal
/// This is used for internal logging of this library.
/// </summary>
[EventSource(Name = "OpenTelemetry.Extensions.Propagators")]
internal class OpenTelemetryPropagatorsEventSource : EventSource
internal sealed class OpenTelemetryPropagatorsEventSource : EventSource
{
public static OpenTelemetryPropagatorsEventSource Log = new();

View File

@ -2,8 +2,12 @@ OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.AspNetCoreInstrumentationOptions() -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnableGrpcAspNetCoreSupport.get -> bool
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnableGrpcAspNetCoreSupport.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Enrich.get -> System.Action<System.Diagnostics.Activity, string, object>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Enrich.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithException.get -> System.Action<System.Diagnostics.Activity, System.Exception>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithException.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpRequest.get -> System.Action<System.Diagnostics.Activity, Microsoft.AspNetCore.Http.HttpRequest>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpRequest.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpResponse.get -> System.Action<System.Diagnostics.Activity, Microsoft.AspNetCore.Http.HttpResponse>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpResponse.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Filter.get -> System.Func<Microsoft.AspNetCore.Http.HttpContext, bool>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Filter.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.RecordException.get -> bool
@ -13,4 +17,4 @@ OpenTelemetry.Trace.TracerProviderBuilderExtensions
static OpenTelemetry.Metrics.MeterProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Metrics.MeterProviderBuilder builder) -> OpenTelemetry.Metrics.MeterProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, string name, System.Action<OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions> configureAspNetCoreInstrumentationOptions) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, System.Action<OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions> configureAspNetCoreInstrumentationOptions) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, System.Action<OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions> configureAspNetCoreInstrumentationOptions) -> OpenTelemetry.Trace.TracerProviderBuilder

View File

@ -2,8 +2,12 @@ OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.AspNetCoreInstrumentationOptions() -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnableGrpcAspNetCoreSupport.get -> bool
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnableGrpcAspNetCoreSupport.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Enrich.get -> System.Action<System.Diagnostics.Activity, string, object>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Enrich.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithException.get -> System.Action<System.Diagnostics.Activity, System.Exception>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithException.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpRequest.get -> System.Action<System.Diagnostics.Activity, Microsoft.AspNetCore.Http.HttpRequest>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpRequest.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpResponse.get -> System.Action<System.Diagnostics.Activity, Microsoft.AspNetCore.Http.HttpResponse>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpResponse.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Filter.get -> System.Func<Microsoft.AspNetCore.Http.HttpContext, bool>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Filter.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.RecordException.get -> bool
@ -13,4 +17,4 @@ OpenTelemetry.Trace.TracerProviderBuilderExtensions
static OpenTelemetry.Metrics.MeterProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Metrics.MeterProviderBuilder builder) -> OpenTelemetry.Metrics.MeterProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, string name, System.Action<OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions> configureAspNetCoreInstrumentationOptions) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, System.Action<OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions> configureAspNetCoreInstrumentationOptions) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, System.Action<OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions> configureAspNetCoreInstrumentationOptions) -> OpenTelemetry.Trace.TracerProviderBuilder

View File

@ -1,7 +1,11 @@
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.AspNetCoreInstrumentationOptions() -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Enrich.get -> System.Action<System.Diagnostics.Activity, string, object>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Enrich.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithException.get -> System.Action<System.Diagnostics.Activity, System.Exception>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithException.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpRequest.get -> System.Action<System.Diagnostics.Activity, Microsoft.AspNetCore.Http.HttpRequest>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpRequest.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpResponse.get -> System.Action<System.Diagnostics.Activity, Microsoft.AspNetCore.Http.HttpResponse>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpResponse.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Filter.get -> System.Func<Microsoft.AspNetCore.Http.HttpContext, bool>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Filter.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.RecordException.get -> bool
@ -9,4 +13,6 @@ OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Record
OpenTelemetry.Metrics.MeterProviderBuilderExtensions
OpenTelemetry.Trace.TracerProviderBuilderExtensions
static OpenTelemetry.Metrics.MeterProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Metrics.MeterProviderBuilder builder) -> OpenTelemetry.Metrics.MeterProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, System.Action<OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions> configureAspNetCoreInstrumentationOptions = null) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, string name, System.Action<OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions> configureAspNetCoreInstrumentationOptions) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, System.Action<OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions> configureAspNetCoreInstrumentationOptions) -> OpenTelemetry.Trace.TracerProviderBuilder

View File

@ -2,8 +2,12 @@ OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.AspNetCoreInstrumentationOptions() -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnableGrpcAspNetCoreSupport.get -> bool
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnableGrpcAspNetCoreSupport.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Enrich.get -> System.Action<System.Diagnostics.Activity, string, object>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Enrich.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithException.get -> System.Action<System.Diagnostics.Activity, System.Exception>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithException.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpRequest.get -> System.Action<System.Diagnostics.Activity, Microsoft.AspNetCore.Http.HttpRequest>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpRequest.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpResponse.get -> System.Action<System.Diagnostics.Activity, Microsoft.AspNetCore.Http.HttpResponse>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.EnrichWithHttpResponse.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Filter.get -> System.Func<Microsoft.AspNetCore.Http.HttpContext, bool>
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Filter.set -> void
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.RecordException.get -> bool
@ -11,4 +15,6 @@ OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions.Record
OpenTelemetry.Metrics.MeterProviderBuilderExtensions
OpenTelemetry.Trace.TracerProviderBuilderExtensions
static OpenTelemetry.Metrics.MeterProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Metrics.MeterProviderBuilder builder) -> OpenTelemetry.Metrics.MeterProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, System.Action<OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions> configureAspNetCoreInstrumentationOptions = null) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, string name, System.Action<OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions> configureAspNetCoreInstrumentationOptions) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddAspNetCoreInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, System.Action<OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions> configureAspNetCoreInstrumentationOptions) -> OpenTelemetry.Trace.TracerProviderBuilder

View File

@ -22,7 +22,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore
/// <summary>
/// Asp.Net Core Requests instrumentation.
/// </summary>
internal class AspNetCoreInstrumentation : IDisposable
internal sealed class AspNetCoreInstrumentation : IDisposable
{
private static readonly HashSet<string> DiagnosticSourceEvents = new()
{

View File

@ -38,11 +38,27 @@ namespace OpenTelemetry.Instrumentation.AspNetCore
/// </summary>
/// <remarks>
/// <para><see cref="Activity"/>: the activity being enriched.</para>
/// <para>string: the name of the event.</para>
/// <para>object: the raw object from which additional information can be extracted to enrich the activity.
/// The type of this object depends on the event, which is given by the above parameter.</para>
/// <para><see cref="HttpRequest"/>: the HttpRequest object from which additional information can be extracted to enrich the activity.</para>
/// </remarks>
public Action<Activity, string, object> Enrich { get; set; }
public Action<Activity, HttpRequest> EnrichWithHttpRequest { get; set; }
/// <summary>
/// Gets or sets an action to enrich an Activity.
/// </summary>
/// <remarks>
/// <para><see cref="Activity"/>: the activity being enriched.</para>
/// <para><see cref="HttpResponse"/>: the HttpResponse object from which additional information can be extracted to enrich the activity.</para>
/// </remarks>
public Action<Activity, HttpResponse> EnrichWithHttpResponse { get; set; }
/// <summary>
/// Gets or sets an action to enrich an Activity.
/// </summary>
/// <remarks>
/// <para><see cref="Activity"/>: the activity being enriched.</para>
/// <para><see cref="Exception"/>: the Exception object from which additional information can be extracted to enrich the activity.</para>
/// </remarks>
public Action<Activity, Exception> EnrichWithException { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the exception will be recorded as ActivityEvent or not.

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore
/// <summary>
/// Asp.Net Core Requests instrumentation.
/// </summary>
internal class AspNetCoreMetrics : IDisposable
internal sealed class AspNetCoreMetrics : IDisposable
{
internal static readonly AssemblyName AssemblyName = typeof(HttpInListener).Assembly.GetName();
internal static readonly string InstrumentationName = AssemblyName.Name;

View File

@ -2,6 +2,24 @@
## Unreleased
* **Breaking change** The `Enrich` callback option has been removed.
For better usability, it has been replaced by three separate options:
`EnrichWithHttpRequest`, `EnrichWithHttpResponse` and `EnrichWithException`.
Previously, the single `Enrich` callback required the consumer to detect
which event triggered the callback to be invoked (e.g., request start,
response end, or an exception) and then cast the object received to the
appropriate type: `HttpRequest`, `HttpResponse`, or `Exception`. The separate
callbacks make it clear what event triggers them and there is no longer the
need to cast the argument to the expected type.
([#3749](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3749))
* Added back `netstandard2.0` and `netstandard2.1` targets.
([#3755](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3755))
## 1.0.0-rc9.8
Released 2022-Oct-17
## 1.0.0-rc9.7
Released 2022-Sep-29

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
/// EventSource events emitted from the project.
/// </summary>
[EventSource(Name = "OpenTelemetry-Instrumentation-AspNetCore")]
internal class AspNetCoreInstrumentationEventSource : EventSource
internal sealed class AspNetCoreInstrumentationEventSource : EventSource
{
public static AspNetCoreInstrumentationEventSource Log = new();

View File

@ -19,11 +19,17 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
#if !NETSTANDARD2_0
using System.Runtime.CompilerServices;
#endif
using Microsoft.AspNetCore.Http;
#if NET6_0_OR_GREATER
using Microsoft.AspNetCore.Mvc.Diagnostics;
#endif
using OpenTelemetry.Context.Propagation;
#if !NETSTANDARD2_0
using OpenTelemetry.Instrumentation.GrpcNetClient;
#endif
using OpenTelemetry.Internal;
using OpenTelemetry.Trace;
@ -52,6 +58,11 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
private const string UnknownHostName = "UNKNOWN-HOST";
private static readonly Func<HttpRequest, string, IEnumerable<string>> HttpRequestHeaderValuesGetter = (request, name) => request.Headers[name];
#if !NET6_0_OR_GREATER
private readonly PropertyFetcher<object> beforeActionActionDescriptorFetcher = new("actionDescriptor");
private readonly PropertyFetcher<object> beforeActionAttributeRouteInfoFetcher = new("AttributeRouteInfo");
private readonly PropertyFetcher<string> beforeActionTemplateFetcher = new("Template");
#endif
private readonly PropertyFetcher<Exception> stopExceptionFetcher = new("Exception");
private readonly AspNetCoreInstrumentationOptions options;
@ -211,7 +222,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
try
{
this.options.Enrich?.Invoke(activity, "OnStartActivity", request);
this.options.EnrichWithHttpRequest?.Invoke(activity, request);
}
catch (Exception ex)
{
@ -235,6 +246,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
activity.SetTag(SemanticConventions.AttributeHttpStatusCode, response.StatusCode);
#if !NETSTANDARD2_0
if (this.options.EnableGrpcAspNetCoreSupport && TryGetGrpcMethod(activity, out var grpcMethod))
{
AddGrpcAttributes(activity, grpcMethod, context);
@ -243,10 +255,16 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
{
activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode(activity.Kind, response.StatusCode));
}
#else
if (activity.Status == ActivityStatusCode.Unset)
{
activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode(activity.Kind, response.StatusCode));
}
#endif
try
{
this.options.Enrich?.Invoke(activity, "OnStopActivity", response);
this.options.EnrichWithHttpResponse?.Invoke(activity, response);
}
catch (Exception ex)
{
@ -310,8 +328,14 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
if (activity.IsAllDataRequested)
{
#if !NET6_0_OR_GREATER
_ = this.beforeActionActionDescriptorFetcher.TryFetch(payload, out var actionDescriptor);
_ = this.beforeActionAttributeRouteInfoFetcher.TryFetch(actionDescriptor, out var attributeRouteInfo);
_ = this.beforeActionTemplateFetcher.TryFetch(attributeRouteInfo, out var template);
#else
var beforeActionEventData = payload as BeforeActionEventData;
var template = beforeActionEventData.ActionDescriptor?.AttributeRouteInfo?.Template;
#endif
if (!string.IsNullOrEmpty(template))
{
// override the span name that was previously set to the path part of URL.
@ -345,7 +369,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
try
{
this.options.Enrich?.Invoke(activity, "OnException", exc);
this.options.EnrichWithException?.Invoke(activity, exc);
}
catch (Exception ex)
{
@ -368,6 +392,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
var length = scheme.Length + Uri.SchemeDelimiter.Length + host.Length + pathBase.Length
+ path.Length + queryString.Length;
#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
return string.Create(length, (scheme, host, pathBase, path, queryString), (span, parts) =>
{
CopyTo(ref span, parts.scheme);
@ -386,8 +411,19 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
}
}
});
#else
return new System.Text.StringBuilder(length)
.Append(scheme)
.Append(Uri.SchemeDelimiter)
.Append(host)
.Append(pathBase)
.Append(path)
.Append(queryString)
.ToString();
#endif
}
#if !NETSTANDARD2_0
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryGetGrpcMethod(Activity activity, out string grpcMethod)
{
@ -435,5 +471,6 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
}
}
}
#endif
}
}

View File

@ -17,12 +17,14 @@
using System.Diagnostics;
using System.Diagnostics.Metrics;
using Microsoft.AspNetCore.Http;
#if NET6_0_OR_GREATER
using Microsoft.AspNetCore.Routing;
#endif
using OpenTelemetry.Trace;
namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
{
internal class HttpInMetricsListener : ListenerHandler
internal sealed class HttpInMetricsListener : ListenerHandler
{
private const string OnStopEvent = "Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop";
@ -67,7 +69,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
}
TagList tags;
#if NET6_0_OR_GREATER
var target = (context.GetEndpoint() as RouteEndpoint)?.RoutePattern.RawText;
// TODO: This is just a minimal set of attributes. See the spec for additional attributes:
@ -95,6 +97,17 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
{ SemanticConventions.AttributeHttpStatusCode, context.Response.StatusCode.ToString() },
};
}
#else
tags = new TagList
{
{ SemanticConventions.AttributeHttpFlavor, context.Request.Protocol },
{ SemanticConventions.AttributeHttpScheme, context.Request.Scheme },
{ SemanticConventions.AttributeHttpMethod, context.Request.Method },
{ SemanticConventions.AttributeHttpHost, host },
{ SemanticConventions.AttributeHttpStatusCode, context.Response.StatusCode.ToString() },
};
#endif
this.httpServerDuration.Record(Activity.Current.Duration.TotalMilliseconds, tags);
}

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- OmniSharp/VS Code requires TargetFrameworks to be in descending order for IntelliSense and analysis. -->
<TargetFrameworks>net7.0;net6.0</TargetFrameworks>
<TargetFrameworks>net7.0;net6.0;netstandard2.1;netstandard2.0</TargetFrameworks>
<Description>ASP.NET Core instrumentation for OpenTelemetry .NET</Description>
<PackageTags>$(PackageTags);distributed-tracing;AspNetCore</PackageTags>
<IncludeDiagnosticSourceInstrumentationHelpers>true</IncludeDiagnosticSourceInstrumentationHelpers>
@ -17,6 +17,16 @@
<ProjectReference Include="$(RepoRoot)\src\OpenTelemetry\OpenTelemetry.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="$(MicrosoftAspNetCoreHttpAbstractionsPkgVer)" />
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="$(MicrosoftAspNetCoreHttpFeaturesPkgVer)" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.1'">
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="$(MicrosoftAspNetCoreHttpAbstractionsPkgVer)" />
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="$(MicrosoftAspNetCoreHttpFeaturesPkgVer)" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net6.0'">
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

View File

@ -120,36 +120,33 @@ and the `Filter` option does the filtering *after* the Sampler is invoked.
### Enrich
This option allows one to enrich the activity with additional information
from the raw `HttpRequest`, `HttpResponse` objects. The `Enrich` action is
called only when `activity.IsAllDataRequested` is `true`. It contains the
activity itself (which can be enriched), the name of the event, and the
actual raw object.
For event name "OnStartActivity", the actual object will be `HttpRequest`.
For event name "OnStopActivity", the actual object will be `HttpResponse`
This instrumentation library provides `EnrichWithHttpRequest`,
`EnrichWithHttpResponse` and `EnrichWithException` options that can be used to
enrich the activity with additional information from the raw `HttpRequest`,
`HttpResponse` and `Exception` objects respectively. These actions are called
only when `activity.IsAllDataRequested` is `true`. It contains the activity
itself (which can be enriched) and the actual raw object.
The following code snippet shows how to add additional tags using `Enrich`.
The following code snippet shows how to enrich the activity using all 3
different options.
```csharp
services.AddOpenTelemetryTracing((builder) =>
{
builder.AddAspNetCoreInstrumentation((options) => options.Enrich
= (activity, eventName, rawObject) =>
builder.AddAspNetCoreInstrumentation(o =>
{
if (eventName.Equals("OnStartActivity"))
o.EnrichWithHttpRequest = (activity, httpRequest) =>
{
if (rawObject is HttpRequest httpRequest)
{
activity.SetTag("requestProtocol", httpRequest.Protocol);
}
}
else if (eventName.Equals("OnStopActivity"))
activity.SetTag("requestProtocol", httpRequest.Protocol);
};
o.EnrichWithHttpResponse = (activity, httpResponse) =>
{
if (rawObject is HttpResponse httpResponse)
{
activity.SetTag("responseLength", httpResponse.ContentLength);
}
}
activity.SetTag("responseLength", httpResponse.ContentLength);
};
o.EnrichWithException = (activity, exception) =>
{
activity.SetTag("exceptionType", exception.GetType().ToString());
};
})
});
```

View File

@ -1,6 +1,8 @@
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.Enrich.get -> System.Action<System.Diagnostics.Activity, string, object>
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.Enrich.set -> void
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.EnrichWithHttpRequestMessage.get -> System.Action<System.Diagnostics.Activity, System.Net.Http.HttpRequestMessage>
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.EnrichWithHttpRequestMessage.set -> void
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.EnrichWithHttpResponseMessage.get -> System.Action<System.Diagnostics.Activity, System.Net.Http.HttpResponseMessage>
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.EnrichWithHttpResponseMessage.set -> void
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.GrpcClientInstrumentationOptions() -> void
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.SuppressDownstreamInstrumentation.get -> bool
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.SuppressDownstreamInstrumentation.set -> void

View File

@ -1,6 +1,8 @@
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.Enrich.get -> System.Action<System.Diagnostics.Activity, string, object>
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.Enrich.set -> void
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.EnrichWithHttpRequestMessage.get -> System.Action<System.Diagnostics.Activity, System.Net.Http.HttpRequestMessage>
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.EnrichWithHttpRequestMessage.set -> void
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.EnrichWithHttpResponseMessage.get -> System.Action<System.Diagnostics.Activity, System.Net.Http.HttpResponseMessage>
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.EnrichWithHttpResponseMessage.set -> void
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.GrpcClientInstrumentationOptions() -> void
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.SuppressDownstreamInstrumentation.get -> bool
OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions.SuppressDownstreamInstrumentation.set -> void

View File

@ -2,6 +2,21 @@
## Unreleased
**Breaking change** The `Enrich` callback option has been removed. For better
usability, it has been replaced by two separate options:
`EnrichWithHttpRequestMessage`and `EnrichWithHttpResponseMessage`. Previously,
the single `Enrich` callback required the consumer to detect which event
triggered the callback to be invoked (e.g., request start or response end) and
then cast the object received to the appropriate type: `HttpRequestMessage`
and `HttpResponseMessage`. The separate callbacks make it clear what event
triggers them and there is no longer the need to cast the argument to the
expected type.
([#3804](https://github.com/open-telemetry/opentelemetry-dotnet/pull/3804))
## 1.0.0-rc9.8
Released 2022-Oct-17
## 1.0.0-rc9.7
Released 2022-Sep-29

View File

@ -21,7 +21,7 @@ namespace OpenTelemetry.Instrumentation.GrpcNetClient
/// <summary>
/// GrpcClient instrumentation.
/// </summary>
internal class GrpcClientInstrumentation : IDisposable
internal sealed class GrpcClientInstrumentation : IDisposable
{
private readonly DiagnosticSourceSubscriber diagnosticSourceSubscriber;

View File

@ -16,6 +16,7 @@
using System;
using System.Diagnostics;
using System.Net.Http;
namespace OpenTelemetry.Instrumentation.GrpcNetClient
{
@ -30,14 +31,21 @@ namespace OpenTelemetry.Instrumentation.GrpcNetClient
public bool SuppressDownstreamInstrumentation { get; set; }
/// <summary>
/// Gets or sets an action to enrich an Activity.
/// Gets or sets an action to enrich the Activity with <see cref="HttpRequestMessage"/>.
/// </summary>
/// <remarks>
/// <para><see cref="Activity"/>: the activity being enriched.</para>
/// <para>string: the name of the event.</para>
/// <para>object: the raw object from which additional information can be extracted to enrich the activity.
/// The type of this object depends on the event, which is given by the above parameter.</para>
/// <para><see cref="HttpRequestMessage"/> object from which additional information can be extracted to enrich the activity.</para>
/// </remarks>
public Action<Activity, string, object> Enrich { get; set; }
public Action<Activity, HttpRequestMessage> EnrichWithHttpRequestMessage { get; set; }
/// <summary>
/// Gets or sets an action to enrich an Activity with <see cref="HttpResponseMessage"/>.
/// </summary>
/// <remarks>
/// <para><see cref="Activity"/>: the activity being enriched.</para>
/// <para><see cref="HttpResponseMessage"/> object from which additional information can be extracted to enrich the activity.</para>
/// </remarks>
public Action<Activity, HttpResponseMessage> EnrichWithHttpResponseMessage { get; set; }
}
}

View File

@ -150,7 +150,7 @@ namespace OpenTelemetry.Instrumentation.GrpcNetClient.Implementation
try
{
this.options.Enrich?.Invoke(activity, "OnStartActivity", request);
this.options.EnrichWithHttpRequestMessage?.Invoke(activity, request);
}
catch (Exception ex)
{
@ -182,7 +182,7 @@ namespace OpenTelemetry.Instrumentation.GrpcNetClient.Implementation
{
try
{
this.options.Enrich?.Invoke(activity, "OnStopActivity", response);
this.options.EnrichWithHttpResponseMessage?.Invoke(activity, response);
}
catch (Exception ex)
{

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.Instrumentation.GrpcNetClient.Implementation
/// EventSource events emitted from the project.
/// </summary>
[EventSource(Name = "OpenTelemetry-Instrumentation-Grpc")]
internal class GrpcInstrumentationEventSource : EventSource
internal sealed class GrpcInstrumentationEventSource : EventSource
{
public static GrpcInstrumentationEventSource Log = new();

Some files were not shown because too many files have changed in this diff Show More