Skip to content

Commit

Permalink
Merge pull request #790 from MicrosoftDocs/main
Browse files Browse the repository at this point in the history
12/12/2024 PM Publish
  • Loading branch information
Taojunshen authored Dec 12, 2024
2 parents db34d6a + 5952abc commit 2888a49
Show file tree
Hide file tree
Showing 5 changed files with 414 additions and 271 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ The Azure Monitor Agent is the new, consolidated telemetry agent for collecting

## Prerequisites

You will need an existing compute resource (virtual machine, virtual machine scale set, or Arc-enabled server). The machine to which Azure Monitor Agent is deployed must have system-assigned managed identity enabled or a user-assigned managed identity associated it to it. We highly recommend using [user-assigned managed identity](/azure/active-directory/managed-identities-azure-resources/how-manage-user-assigned-managed-identities) for better scalability and performance. Azure Monitor Agent must be configured to use this managed identity for authentication as described in the [prerequisites](azure-monitor-agent-requirements.md#permissions).
You will need an existing compute resource (such as virtual machine or virtual machine scale set. The machine to which Azure Monitor Agent is deployed must have system-assigned managed identity enabled or a user-assigned managed identity associated it to it. We highly recommend using [user-assigned managed identity](/azure/active-directory/managed-identities-azure-resources/how-manage-user-assigned-managed-identities) for better scalability and performance. Azure Monitor Agent must be configured to use this managed identity for authentication as described in the [prerequisites](azure-monitor-agent-requirements.md#permissions).

You must provision the necessary [storage account(s)](/azure/storage/common/storage-account-create) and/or [Event Hubs](/azure/event-hubs/event-hubs-create) to which you wish to publish data via Azure Monitor Agent. Additionally, the proper built-in RBAC role(s) must be assigned to the chosen managed identity per your desired data destination(s):

Expand Down
8 changes: 4 additions & 4 deletions articles/azure-monitor/app/asp-net-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ For Visual Studio for Mac, use the [manual guidance](#enable-application-insight
},
"AllowedHosts": "*",
"ApplicationInsights": {
"ConnectionString": "Copy connection string from Application Insights Resource Overview"
"ConnectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000"
}
}
```
Expand Down Expand Up @@ -171,7 +171,7 @@ using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPuls

// Create a TelemetryConfiguration instance.
TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
config.InstrumentationKey = "INSTRUMENTATION-KEY-HERE";
config.ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000";
QuickPulseTelemetryProcessor quickPulseProcessor = null;
config.DefaultTelemetrySink.TelemetryProcessorChainBuilder
.Use((next) =>
Expand Down Expand Up @@ -322,7 +322,7 @@ In Microsoft.ApplicationInsights.AspNetCore SDK version [2.15.0](https://www.nug
```json
{
"ApplicationInsights": {
"ConnectionString": "Copy connection string from Application Insights Resource Overview",
"ConnectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000",
"EnableAdaptiveSampling": false,
"EnablePerformanceCounterCollectionModule": false
}
Expand Down Expand Up @@ -640,7 +640,7 @@ When you add Application Insights Telemetry to a Visual Studio ASP.NET Core temp

```json
"ApplicationInsights": {
"InstrumentationKey": "00000000-0000-0000-0000-000000000000"
"ConnectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000"
}
```

Expand Down
270 changes: 4 additions & 266 deletions articles/azure-monitor/app/opentelemetry-add-modify.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: Add, modify, and filter Azure Monitor OpenTelemetry for .NET, Java, Node.js, and Python applications
description: This article provides guidance on how to add, modify, and filter OpenTelemetry for applications using Azure Monitor.
title: Add and modify Azure Monitor OpenTelemetry for .NET, Java, Node.js, and Python applications
description: This article provides guidance on how to add and modify OpenTelemetry for applications using Azure Monitor.
ms.topic: conceptual
ms.date: 12/07/2024
ms.devlang: csharp
Expand All @@ -9,9 +9,9 @@ ms.custom: devx-track-dotnet, devx-track-extended-java, devx-track-python
ms.reviewer: mmcc
---

# Add, modify, and filter OpenTelemetry
# Add and modify Azure Monitor OpenTelemetry for .NET, Java, Node.js, and Python applications

This article provides guidance on how to add, modify, and filter OpenTelemetry for applications using [Azure Monitor Application Insights](app-insights-overview.md#application-insights-overview).
This article provides guidance on how to add and modify OpenTelemetry for applications using [Azure Monitor Application Insights](app-insights-overview.md#application-insights-overview).

To learn more about OpenTelemetry concepts, see the [OpenTelemetry overview](opentelemetry-overview.md) or [OpenTelemetry FAQ](opentelemetry-help-support-feedback.md).

Expand Down Expand Up @@ -2313,269 +2313,7 @@ logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})

---

## Filter telemetry

You might use the following ways to filter out telemetry before it leaves your application.

### [ASP.NET Core](#tab/aspnetcore)

1. Many instrumentation libraries provide a filter option. For guidance, see the readme files of individual instrumentation libraries:

* [ASP.NET Core](https://github.com/open-telemetry/opentelemetry-dotnet/blob/1.0.0-rc9.14/src/OpenTelemetry.Instrumentation.AspNetCore/README.md#filter)
* [HttpClient](https://github.com/open-telemetry/opentelemetry-dotnet/blob/1.0.0-rc9.14/src/OpenTelemetry.Instrumentation.Http/README.md#filter)
1. Use a custom processor:

> [!TIP]
> Add the processor shown here *before* adding Azure Monitor.

```csharp
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the OpenTelemetry tracer provider to add a new processor named ActivityFilteringProcessor.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddProcessor(new ActivityFilteringProcessor()));
// Configure the OpenTelemetry tracer provider to add a new source named "ActivitySourceName".
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();

// Build the ASP.NET Core application.
var app = builder.Build();

// Start the ASP.NET Core application.
app.Run();
```

Add `ActivityFilteringProcessor.cs` to your project with the following code:

```csharp
public class ActivityFilteringProcessor : BaseProcessor<Activity>
{
// The OnStart method is called when an activity is started. This is the ideal place to filter activities.
public override void OnStart(Activity activity)
{
// prevents all exporters from exporting internal activities
if (activity.Kind == ActivityKind.Internal)
{
activity.IsAllDataRequested = false;
}
}
}
```

1. If a particular source isn't explicitly added by using `AddSource("ActivitySourceName")`, then none of the activities created by using that source are exported.

### [.NET](#tab/net)

1. Many instrumentation libraries provide a filter option. For guidance, see the readme files of individual instrumentation libraries:

* [ASP.NET](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/blob/Instrumentation.AspNet-1.0.0-rc9.8/src/OpenTelemetry.Instrumentation.AspNet/README.md#filter)
* [ASP.NET Core](https://github.com/open-telemetry/opentelemetry-dotnet/blob/1.0.0-rc9.14/src/OpenTelemetry.Instrumentation.AspNetCore/README.md#filter)
* [HttpClient](https://github.com/open-telemetry/opentelemetry-dotnet/blob/1.0.0-rc9.14/src/OpenTelemetry.Instrumentation.Http/README.md#filter)
1. Use a custom processor:

```csharp
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("OTel.AzureMonitor.Demo") // Add a source named "OTel.AzureMonitor.Demo".
.AddProcessor(new ActivityFilteringProcessor()) // Add a new processor named ActivityFilteringProcessor.
.AddAzureMonitorTraceExporter() // Add the Azure Monitor trace exporter.
.Build();
```

Add `ActivityFilteringProcessor.cs` to your project with the following code:

```csharp
public class ActivityFilteringProcessor : BaseProcessor<Activity>
{
// The OnStart method is called when an activity is started. This is the ideal place to filter activities.
public override void OnStart(Activity activity)
{
// prevents all exporters from exporting internal activities
if (activity.Kind == ActivityKind.Internal)
{
activity.IsAllDataRequested = false;
}
}
}
```

1. If a particular source isn't explicitly added by using `AddSource("ActivitySourceName")`, then none of the activities created by using that source are exported.

### [Java](#tab/java)

See [sampling overrides](java-standalone-config.md#sampling-overrides) and [telemetry processors](java-standalone-telemetry-processors.md).

### [Java native](#tab/java-native)

It's not possible to filter telemetry in Java native.

### [Node.js](#tab/nodejs)

1. Exclude the URL option provided by many HTTP instrumentation libraries.

The following example shows how to exclude a certain URL from being tracked by using the [HTTP/HTTPS instrumentation library](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http):
```typescript
// Import the useAzureMonitor function and the ApplicationInsightsOptions class from the @azure/monitor-opentelemetry package.
const { useAzureMonitor, ApplicationInsightsOptions } = require("@azure/monitor-opentelemetry");

// Import the HttpInstrumentationConfig class from the @opentelemetry/instrumentation-http package.
const { HttpInstrumentationConfig }= require("@opentelemetry/instrumentation-http");

// Import the IncomingMessage and RequestOptions classes from the http and https packages, respectively.
const { IncomingMessage } = require("http");
const { RequestOptions } = require("https");

// Create a new HttpInstrumentationConfig object.
const httpInstrumentationConfig: HttpInstrumentationConfig = {
enabled: true,
ignoreIncomingRequestHook: (request: IncomingMessage) => {
// Ignore OPTIONS incoming requests.
if (request.method === 'OPTIONS') {
return true;
}
return false;
},
ignoreOutgoingRequestHook: (options: RequestOptions) => {
// Ignore outgoing requests with the /test path.
if (options.path === '/test') {
return true;
}
return false;
}
};

// Create a new ApplicationInsightsOptions object.
const config: ApplicationInsightsOptions = {
instrumentationOptions: {
http: {
httpInstrumentationConfig
}
}
};

// Enable Azure Monitor integration using the useAzureMonitor function and the ApplicationInsightsOptions object.
useAzureMonitor(config);
```

1. Use a custom processor. You can use a custom span processor to exclude certain spans from being exported. To mark spans to not be exported, set `TraceFlag` to `DEFAULT`.

Use the [custom property example](#add-a-custom-property-to-a-span), but replace the following lines of code:

```typescript
// Import the necessary packages.
const { SpanKind, TraceFlags } = require("@opentelemetry/api");
const { ReadableSpan, Span, SpanProcessor } = require("@opentelemetry/sdk-trace-base");

// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
forceFlush(): Promise<void> {
return Promise.resolve();
}

shutdown(): Promise<void> {
return Promise.resolve();
}

onStart(_span: Span): void {}

onEnd(span) {
// If the span is an internal span, set the trace flags to NONE.
if(span.kind == SpanKind.INTERNAL){
span.spanContext().traceFlags = TraceFlags.NONE;
}
}
}
```

### [Python](#tab/python)

1. Exclude the URL with the `OTEL_PYTHON_EXCLUDED_URLS` environment variable:

```
export OTEL_PYTHON_EXCLUDED_URLS="http://localhost:8080/ignore"
```
Doing so excludes the endpoint shown in the following Flask example:

```python
...
# Import the Flask and Azure Monitor OpenTelemetry SDK libraries.
import flask
from azure.monitor.opentelemetry import configure_azure_monitor

# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)

# Create a Flask application.
app = flask.Flask(__name__)

# Define a route. Requests sent to this endpoint will not be tracked due to
# flask_config configuration.
@app.route("/ignore")
def ignore():
return "Request received but not tracked."
...
```

1. Use a custom processor. You can use a custom span processor to exclude certain spans from being exported. To mark spans to not be exported, set `TraceFlag` to `DEFAULT`:

```python
...
# Import the necessary libraries.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace

# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
# Configure the custom span processors to include span filter processor.
span_processors=[span_filter_processor],
)

...
```

Add `SpanFilteringProcessor` to your project with the following code:

```python
# Import the necessary libraries.
from opentelemetry.trace import SpanContext, SpanKind, TraceFlags
from opentelemetry.sdk.trace import SpanProcessor

# Define a custom span processor called `SpanFilteringProcessor`.
class SpanFilteringProcessor(SpanProcessor):

# Prevents exporting spans from internal activities.
def on_start(self, span, parent_context):
# Check if the span is an internal activity.
if span._kind is SpanKind.INTERNAL:
# Create a new span context with the following properties:
# * The trace ID is the same as the trace ID of the original span.
# * The span ID is the same as the span ID of the original span.
# * The is_remote property is set to `False`.
# * The trace flags are set to `DEFAULT`.
# * The trace state is the same as the trace state of the original span.
span._context = SpanContext(
span.context.trace_id,
span.context.span_id,
span.context.is_remote,
TraceFlags(TraceFlags.DEFAULT),
span.context.trace_state,
)

```

---

<!-- For more information, see [GitHub Repo](link). -->

## Get the trace ID or span ID

Expand Down
Loading

0 comments on commit 2888a49

Please sign in to comment.