Den här guiden beskriver hur du konfigurerar OpenTelemetry (OTel) i Azure Monitor Application Insights med hjälp av Azure Monitor OpenTelemetry-distributionen. Korrekt konfiguration säkerställer konsekvent insamling av telemetridata i .NET-, Java-, Node.js- och Python-program, vilket möjliggör mer tillförlitlig övervakning och diagnostik.
Anslutningssträng
En anslutningssträng i Application Insights definierar målplatsen för att skicka telemetridata.
Använd något av följande tre sätt att konfigurera anslutningssträng:
- Lägg till UseAzureMonitor()iprogram.csfilen:
    var builder = WebApplication.CreateBuilder(args);
    // Add the OpenTelemetry telemetry service to the application.
    // This service will collect and send telemetry data to Azure Monitor.
    builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
        options.ConnectionString = "<Your Connection String>";
    });
    var app = builder.Build();
    app.Run();
   APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
- Lägg till följande avsnitt i konfigurationsfilen appsettings.json.
  {
    "AzureMonitor": {
        "ConnectionString": "<Your Connection String>"
    }
  }
Anmärkning
Om du anger anslutningssträng på fler än en plats följer vi följande prioritet:
- Kod
- Miljövariabel
- Konfigurationsfil
 
Använd något av följande två sätt att konfigurera anslutningssträng:
- Lägg till Azure Monitor Exporter till varje OpenTelemetry-signal i programstarten.
    // Create a new OpenTelemetry tracer provider.
    // It is important to keep the TracerProvider instance active throughout the process lifetime.
    var tracerProvider = Sdk.CreateTracerProviderBuilder()
        .AddAzureMonitorTraceExporter(options =>
        {
            options.ConnectionString = "<Your Connection String>";
        })
        .Build();
    // Create a new OpenTelemetry meter provider.
    // It is important to keep the MetricsProvider instance active throughout the process lifetime.
    var metricsProvider = Sdk.CreateMeterProviderBuilder()
        .AddAzureMonitorMetricExporter(options =>
        {
            options.ConnectionString = "<Your Connection String>";
        })
        .Build();
    // Create a new logger factory.
    // It is important to keep the LoggerFactory instance active throughout the process lifetime.
    var loggerFactory = LoggerFactory.Create(builder =>
    {
        builder.AddOpenTelemetry(logging =>
        {
            logging.AddAzureMonitorLogExporter(options =>
            {
                options.ConnectionString = "<Your Connection String>";
            });
        });
    });
   APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
Anmärkning
Om du anger anslutningssträng på fler än en plats följer vi följande prioritet:
- Kod
- Miljövariabel
 
Använd något av följande två sätt att konfigurera anslutningssträng:
   APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
    applicationinsights.connection.string=<Your Connection String>
Använd något av följande två sätt att konfigurera anslutningssträng:
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
- Använd ett konfigurationsobjekt.
export class BasicConnectionSample {
  static async run() {
    const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
    const options = {
      azureMonitorExporterOptions: {
        connectionString:
          process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
      },
    };
    const monitor = useAzureMonitor(options);
    console.log("Azure Monitor initialized");
  }
}
Använd något av följande två sätt att konfigurera anslutningssträng:
   APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
- 
              configure_azure_monitorAnvänd funktionen.
# Import the `configure_azure_monitor()` function from the `azure.monitor.opentelemetry` package.
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 of your Azure Monitor Application Insights resource.
configure_azure_monitor(
    connection_string="<your-connection-string>",
)
 
Ange namnet på molnrollen och molnrollinstansen
För språk som stöds identifierar Azure Monitor OpenTelemetry Distro automatiskt resurskontexten och tillhandahåller standardvärden för egenskaperna Cloud Role Name och Cloud Role Instance för din komponent. Men du kanske vill åsidosätta standardvärdena till något som passar ditt team. Värdet för molnrollens namn visas på programkartan som namnet under en nod.
Ange namnet på molnrollen och molnrollinstansen via resursattribut . Namnet på molnrollen använder service.namespace och service.name attribut, även om det återgår till service.name om service.namespace inte har angetts. Cloud Role Instance använder service.instance.id attributvärdet. Information om standardattribut för resurser finns i OpenTelemetry Semantiska konventioner.
// Setting role name and role instance
// Create a dictionary of resource attributes.
var resourceAttributes = new Dictionary<string, object> {
    { "service.name", "my-service" },
    { "service.namespace", "my-namespace" },
    { "service.instance.id", "my-instance" }};
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry()
    .UseAzureMonitor()
    // Configure the ResourceBuilder to add the custom resource attributes to all signals.
    // Custom resource attributes should be added AFTER AzureMonitor to override the default ResourceDetectors.
    .ConfigureResource(resourceBuilder => resourceBuilder.AddAttributes(resourceAttributes));
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Ange namnet på molnrollen och molnrollinstansen via resursattribut . Namnet på molnrollen använder service.namespace och service.name attribut, även om det återgår till service.name om service.namespace inte har angetts. Cloud Role Instance använder service.instance.id attributvärdet. Information om standardattribut för resurser finns i OpenTelemetry Semantiska konventioner.
// Setting role name and role instance
// Create a dictionary of resource attributes.
var resourceAttributes = new Dictionary<string, object> {
    { "service.name", "my-service" },
    { "service.namespace", "my-namespace" },
    { "service.instance.id", "my-instance" }};
// Create a resource builder.
var resourceBuilder = ResourceBuilder.CreateDefault().AddAttributes(resourceAttributes);
// Create a new OpenTelemetry tracer provider and set the resource builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
    // Set ResourceBuilder on the TracerProvider.
    .SetResourceBuilder(resourceBuilder)
    .AddAzureMonitorTraceExporter()
    .Build();
// Create a new OpenTelemetry meter provider and set the resource builder.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
    // Set ResourceBuilder on the MeterProvider.
    .SetResourceBuilder(resourceBuilder)
    .AddAzureMonitorMetricExporter()
    .Build();
// Create a new logger factory and add the OpenTelemetry logger provider with the resource builder.
// It is important to keep the LoggerFactory instance active throughout the process lifetime.
var loggerFactory = LoggerFactory.Create(builder =>
{
    builder.AddOpenTelemetry(logging =>
    {
        // Set ResourceBuilder on the Logging config.
        logging.SetResourceBuilder(resourceBuilder);
        logging.AddAzureMonitorLogExporter();
    });
});
Så här anger du namnet på molnrollen:
- Använd spring.application.nameför Spring Boot native image-applikationer
- Använd quarkus.application.nameför Quarkus inbyggda bildapplikationer
Anmärkning
Quarkus-communityn stöder och underhåller Quarkus-tillägg. Om du vill ha hjälp använder du Quarkus community-supportkanaler. Microsoft tillhandahåller inte teknisk support för den här integreringen.
 
Ange namnet på molnrollen och molnrollinstansen via resursattribut . Namnet på molnrollen använder service.namespace och service.name attribut, även om det återgår till service.name om service.namespace inte har angetts. Cloud Role Instance använder service.instance.id attributvärdet. Information om standardattribut för resurser finns i OpenTelemetry Semantiska konventioner.
export class CloudRoleSample {
  static async run() {
    const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
    const { resourceFromAttributes } = await import("@opentelemetry/resources");
    const { ATTR_SERVICE_NAME } = await import("@opentelemetry/semantic-conventions");
    const { ATTR_SERVICE_NAMESPACE, ATTR_SERVICE_INSTANCE_ID } =
      await import("@opentelemetry/semantic-conventions/incubating");
    const customResource = resourceFromAttributes({
      [ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || "my-service",
      [ATTR_SERVICE_NAMESPACE]: process.env.OTEL_SERVICE_NAMESPACE || "my-namespace",
      [ATTR_SERVICE_INSTANCE_ID]: process.env.OTEL_SERVICE_INSTANCE_ID || "my-instance",
    });
    const options = {
      resource: customResource,
      azureMonitorExporterOptions: {
        connectionString:
          process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
      },
    };
    const monitor = useAzureMonitor(options);
    console.log("Azure Monitor initialized (custom resource)");
  }
}
Ange namnet på molnrollen och molnrollinstansen via resursattribut . Namnet på molnrollen använder service.namespace och service.name attribut, även om det återgår till service.name om service.namespace inte har angetts. Cloud Role Instance använder service.instance.id attributvärdet. Information om standardattribut för resurser finns i OpenTelemetry Semantiska konventioner.
Ange resursattribut med hjälp av miljövariablerna OTEL_RESOURCE_ATTRIBUTES och/eller OTEL_SERVICE_NAME. 
              OTEL_RESOURCE_ATTRIBUTES tar en serie av kommaavgränsade nyckel-värdepar. Om du till exempel vill ange namnet på molnrollen till my-namespace.my-helloworld-service och ange Cloud Role Instance till my-instancekan du ange OTEL_RESOURCE_ATTRIBUTES och OTEL_SERVICE_NAME så här:
export OTEL_RESOURCE_ATTRIBUTES="service.namespace=my-namespace,service.instance.id=my-instance"
export OTEL_SERVICE_NAME="my-helloworld-service"
Om du inte anger resursattributet service.namespace kan du också ange namnet på molnrollen med endast miljövariabeln OTEL_SERVICE_NAME eller resursattributet service.name . Om du till exempel vill ange namnet på molnrollen till my-helloworld-service och ange Cloud Role Instance till my-instancekan du ange OTEL_RESOURCE_ATTRIBUTES och OTEL_SERVICE_NAME så här:
export OTEL_RESOURCE_ATTRIBUTES="service.instance.id=my-instance"
export OTEL_SERVICE_NAME="my-helloworld-service"
 
Aktivera sampling
Du kanske vill aktivera sampling för att minska datainmatningsvolymen, vilket minskar kostnaden. Azure Monitor tillhandahåller en anpassad fast samplingshastighet som tilldelar ett samplingsförhållande till händelser, vilket Application Insights konverterar till ItemCount. Sampeln med fast hastighet säkerställer korrekta upplevelser och händelseantal. Samplern är utformad för att bevara dina spår mellan tjänster, och den är kompatibel med äldre Application Insights Software Development Kits (SDK:er). Mer information finns i Läs mer om sampling.
Anmärkning
Mått och loggar påverkas inte av sampling.
Om du ser oväntade avgifter eller höga kostnader i Application Insights kan den här guiden hjälpa dig. Den omfattar vanliga orsaker som hög telemetrivolym, datainmatningstoppar och felkonfigurerad sampling. Det är särskilt användbart om du felsöker problem som rör kostnadstoppar, telemetrivolym, sampling som inte fungerar, datatak, hög inmatning eller oväntad fakturering. Information om hur du kommer igång finns i Felsöka hög datainmatning i Application Insights.
 
Provtagaren förväntar sig en samplingsfrekvens mellan 0 och 1, inklusive. En hastighet på 0,1 innebär att cirka 10 % av dina spårningar skickas.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options =>
{
    // Set the sampling ratio to 10%. This means that 10% of all traces will be sampled and sent to Azure Monitor.
    options.SamplingRatio = 0.1F;
});
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Provtagaren förväntar sig en samplingsfrekvens mellan 0 och 1, inklusive. En hastighet på 0,1 innebär att cirka 10 % av dina spårningar skickas.
// Create a new OpenTelemetry tracer provider.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .AddAzureMonitorTraceExporter(options =>
    {   
        // Set the sampling ratio to 10%. This means that 10% of all traces will be sampled and sent to Azure Monitor.
        options.SamplingRatio = 0.1F;
    })
    .Build();
Från och med 3.4.0 är hastighetsbegränsad sampling tillgänglig och är nu standard. Mer information om sampling finns i Java-sampling.
Frekvensbegränsad sampling är tillgänglig från azure-monitor-opentelemetry-exporter version 1.0.0-beta.32. Konfigurera sampling med hjälp av följande miljövariabler:
- 
              OTEL_TRACES_SAMPLER: Anger exempeltypen
- 
              microsoft.fixed.percentageför Application Insights-samplare
- 
              microsoft.rate_limitedför hastighetsbegränsad sampel
 
- 
              OTEL_TRACES_SAMPLER_ARG: Definierar samplingsfrekvensen
- 
              ApplicationInsightsSampler: Exempeltagaren förväntar sig en exempelfrekvens på mellan 0 och 1 inklusive. En hastighet på 0,1 innebär att cirka 10 % av dina spårningar skickas.
- 
              RateLimitedSampler: Maximalt antal spårningar per sekund (t.ex. 0,5 = en spårning varannan sekund, 5,0 = fem spårningar per sekund)
 
              Alternativ konfiguration
export class FixedRateSamplingSample {
  static async run() {
    // Dynamically import and initialize Azure Monitor with fixed-rate sampling (~10%).
    const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
    const options = {
      samplingRatio: 0.1, // ~10% of traces
      azureMonitorExporterOptions: {
        connectionString:
          process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
      },
    };
    const monitor = useAzureMonitor(options);
    console.log("Azure Monitor initialized (fixed-rate sampling)");
  }
}
export class RateLimitedSamplingSample {
  static async run() {
    // Dynamically import and initialize Azure Monitor with rate-limited sampling (~1.5 traces/sec).
    const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
    const options = {
      tracesPerSecond: 1.5, // ~1.5 traces per second
      azureMonitorExporterOptions: {
        connectionString:
          process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
      },
    };
    const monitor = useAzureMonitor(options);
    console.log("Azure Monitor initialized (rate-limited sampling)");
  }
}
ApplicationInsightsSampler-exempel
export OTEL_TRACES_SAMPLER="microsoft.fixed.percentage"
export OTEL_TRACES_SAMPLER_ARG=0.3
Exempel på RateLimitedSampler
export OTEL_TRACES_SAMPLER="microsoft.rate_limited"
export OTEL_TRACES_SAMPLER_ARG=1.5
Anmärkning
Samplingskonfiguration via miljövariabler har företräde framför alternativen för samplingsexportör/distribution. Om varken miljövariabler eller tracesPerSecond anges, används ApplicationInsightsSampler som standard för sampling.
 
Frekvensbegränsad sampling är tillgänglig från azure-monitor-opentelemetry version 1.8.0. Konfigurera sampling med hjälp av följande miljövariabler:
- 
              OTEL_TRACES_SAMPLER: Anger exempeltypen
- 
              microsoft.fixed.percentageför Application Insights-samplare
- 
              microsoft.rate_limitedför hastighetsbegränsad sampel
 
- 
              OTEL_TRACES_SAMPLER_ARG: Definierar samplingsfrekvensen
- 
              ApplicationInsightsSampler: Giltigt intervall 0 till 1 (0 = 0%, 1 = 100%)
- 
              RateLimitedSampler: Maximalt antal spårningar per sekund (t.ex. 0,5 = en spårning varannan sekund, 5,0 = fem spårningar per sekund)
 
              Alternativ konfiguration: Använd configure_azure_monitor() funktionen med traces_per_second attributet för att aktivera RateLimitedSampler.
Anmärkning
Samplingskonfiguration via miljövariabler har företräde framför alternativen för samplingsexportör/distribution. Om varken miljövariabler eller traces_per_second anges, används configure_azure_monitor() som standard ApplicationInsightsSampler.
 
ApplicationInsightsSampler-exempel
export OTEL_TRACES_SAMPLER="microsoft.fixed.percentage"
export OTEL_TRACES_SAMPLER_ARG=0.1
Exempel på RateLimitedSampler
export OTEL_TRACES_SAMPLER="microsoft.rate_limited"
export OTEL_TRACES_SAMPLER_ARG=0.5
 
Tips
När du använder sampling med fast hastighet/procent och du inte är säker på vad du ska ange samplingsfrekvensen som, börjar du på 5 %. (0,05 samplingsförhållande) Justera hastigheten baserat på noggrannheten för de åtgärder som visas i fel- och prestandafönstret. En högre frekvens resulterar vanligtvis i högre noggrannhet. All sampling påverkar dock noggrannheten, så vi rekommenderar att du skickar aviseringar baserade på OpenTelemetry-mätvärden, som inte påverkas av sampling.
 
Live-metriker
              Realtidsmått erbjuder en realtidsanalysinstrumentpanel för insikt i applikationsaktivitet och prestanda.
Den här funktionen aktiveras som standard.
Användare kan inaktivera Live Metrics när de konfigurerar distributionen.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
	// Disable the Live Metrics feature.
    options.EnableLiveMetrics = false;
});
Den här funktionen är inte tillgänglig i Azure Monitor .NET Exporter.
Live Metrics är inte tillgängliga idag för GraalVM-native applikationer.
Användare kan aktivera/inaktivera Live Metrics när de konfigurerar Distro med egenskapen enableLiveMetrics.
export class LiveMetricsSample {
  static async run() {
    const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
    const options = {
      azureMonitorExporterOptions: {
        connectionString:
          process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
      },
      enableLiveMetrics: true, // set to false to disable
    };
    const monitor = useAzureMonitor(options);
    console.log("Azure Monitor initialized (live metrics enabled)");
  }
}
Du kan aktivera livemått med hjälp av Azure Monitor OpenTelemetry Distro för Python på följande sätt:
...
configure_azure_monitor(
	enable_live_metrics=True
)
...
 
Du kanske vill aktivera Microsoft Entra-autentisering för en säkrare anslutning till Azure, vilket förhindrar att obehörig telemetri matas in i din prenumeration.
Mer information finns på vår dedikerade Microsoft Entra-autentiseringssida länkad för varje språk som stöds.
Microsoft Entra ID-autentisering är inte tillgängligt för GraalVM Native-applikationer.
 
Offlinelagring och automatiska återförsök
Azure Monitor OpenTelemetry-baserade erbjudanden cachelagrar telemetri när ett program kopplas bort från Application Insights och försöker skicka igen i upp till 48 timmar. Rekommendationer för datahantering finns i Exportera och ta bort privata data. Program med hög belastning släpper ibland telemetri av två skäl: överskrider den tillåtna tiden eller överskrider den maximala filstorleken. Vid behov prioriterar produkten de senaste händelserna framför gamla.
Distributionspaketet innehåller AzureMonitorExporter, som som standard använder någon av följande platser för offlinelagring (listad i prioritetsordning):
- Windows 
- %LOCALAPPDATA%\Microsoft\AzureMonitor
- %TEMP%\Microsoft\AzureMonitor
 
- Icke-Windows 
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
- /tmp/Microsoft/AzureMonitor
 
Om du vill åsidosätta standardkatalogen bör du ange AzureMonitorOptions.StorageDirectory.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options =>
{
    // Set the Azure Monitor storage directory to "C:\\SomeDirectory".
    // This is the directory where the OpenTelemetry SDK will store any telemetry data that cannot be sent to Azure Monitor immediately.
    options.StorageDirectory = "C:\\SomeDirectory";
});
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Om du vill inaktivera den här funktionen bör du ange AzureMonitorOptions.DisableOfflineStorage = true.
Som standard använder AzureMonitorExporter någon av följande platser för offlinelagring (listad i prioritetsordning):
- Windows 
- %LOCALAPPDATA%\Microsoft\AzureMonitor
- %TEMP%\Microsoft\AzureMonitor
 
- Icke-Windows 
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
- /tmp/Microsoft/AzureMonitor
 
Om du vill åsidosätta standardkatalogen bör du ange AzureMonitorExporterOptions.StorageDirectory.
// Create a new OpenTelemetry tracer provider and set the storage directory.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .AddAzureMonitorTraceExporter(options =>
    {
        // Set the Azure Monitor storage directory to "C:\\SomeDirectory".
        // This is the directory where the OpenTelemetry SDK will store any trace data that cannot be sent to Azure Monitor immediately.
        options.StorageDirectory = "C:\\SomeDirectory";
        })
        .Build();
// Create a new OpenTelemetry meter provider and set the storage directory.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
    .AddAzureMonitorMetricExporter(options =>
    {
        // Set the Azure Monitor storage directory to "C:\\SomeDirectory".
        // This is the directory where the OpenTelemetry SDK will store any metric data that cannot be sent to Azure Monitor immediately.
        options.StorageDirectory = "C:\\SomeDirectory";
        })
        .Build();
// Create a new logger factory and add the OpenTelemetry logger provider with the storage directory.
// It is important to keep the LoggerFactory instance active throughout the process lifetime.
var loggerFactory = LoggerFactory.Create(builder =>
{
    builder.AddOpenTelemetry(logging =>
    {
        logging.AddAzureMonitorLogExporter(options =>
        {
            // Set the Azure Monitor storage directory to "C:\\SomeDirectory".
            // This is the directory where the OpenTelemetry SDK will store any log data that cannot be sent to Azure Monitor immediately.
            options.StorageDirectory = "C:\\SomeDirectory";
        });
    });
});
Om du vill inaktivera den här funktionen bör du ange AzureMonitorExporterOptions.DisableOfflineStorage = true.
När agenten inte kan skicka telemetri till Azure Monitor lagrar den telemetrifiler på disken. Filerna sparas i en telemetry mapp under den katalog som anges av systemegenskapen java.io.tmpdir . Varje filnamn börjar med en tidsstämpel och slutar med .trn tillägget. Den här offlinelagringsmekanismen hjälper till att säkerställa att telemetri behålls vid tillfälliga nätverksfel eller inmatningsfel.
Agenten lagrar upp till 50 MB telemetridata som standard och tillåter konfiguration av lagringsgränsen. Försök att skicka lagrad telemetri görs regelbundet. Telemetrifiler som är äldre än 48 timmar tas bort och de äldsta händelserna ignoreras när lagringsgränsen nås.
En fullständig lista över tillgängliga konfigurationer finns i Konfigurationsalternativ.
När agenten inte kan skicka telemetri till Azure Monitor lagrar den telemetrifiler på disken. Filerna sparas i en telemetry mapp under den katalog som anges av systemegenskapen java.io.tmpdir . Varje filnamn börjar med en tidsstämpel och slutar med .trn tillägget. Den här offlinelagringsmekanismen hjälper till att säkerställa att telemetri behålls vid tillfälliga nätverksfel eller inmatningsfel.
Agenten lagrar upp till 50 MB telemetridata som standard. Försök att skicka lagrad telemetri görs regelbundet. Telemetrifiler som är äldre än 48 timmar tas bort och de äldsta händelserna ignoreras när lagringsgränsen nås.
Som standard använder AzureMonitorExporter någon av följande platser för offlinelagring.
- Windows 
- %TEMP%\Microsoft\AzureMonitor
 
- Icke-Windows 
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
 
Om du vill åsidosätta standardkatalogen bör du ange storageDirectory.
Till exempel:
export class OfflineStorageSample {
  static async run() {
    const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
    const options = {
      azureMonitorExporterOptions: {
        connectionString:
          process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<Your Connection String>",
        storageDirectory: "C:\\\\SomeDirectory",
        disableOfflineStorage: false, // set to true to disable
      },
    };
    const monitor = useAzureMonitor(options);
    console.log("Azure Monitor initialized (offline storage configured)");
  }
}
Om du vill inaktivera den här funktionen bör du ange disableOfflineStorage = true.
Som standard använder Azure Monitor-exportörer följande sökväg:
<tempfile.gettempdir()>/Microsoft/AzureMonitor/opentelemetry-python-<your-instrumentation-key>
Om du vill åsidosätta standardkatalogen bör du ställa in storage_directory till den katalog du vill ha.
Till exempel:
...
# Configure OpenTelemetry to use Azure Monitor with the specified connection string and storage directory.
# Replace `your-connection-string` with the connection string to your Azure Monitor Application Insights resource.
# Replace `C:\\SomeDirectory` with the directory where you want to store the telemetry data before it is sent to Azure Monitor.
configure_azure_monitor(
    connection_string="your-connection-string",
    storage_directory="C:\\SomeDirectory",
)
...
Om du vill inaktivera den här funktionen bör du ange disable_offline_storage till True. Standardvärdet är False.
Till exempel:
...
# Configure OpenTelemetry to use Azure Monitor with the specified connection string and disable offline storage.
# Replace `your-connection-string` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
    connection_string="your-connection-string",
    disable_offline_storage=True,
)
...
 
Aktivera OTLP-exportören
Du kanske vill aktivera exportör av OpenTelemetry Protocol (OTLP) tillsammans med Azure Monitor Exporter för att skicka telemetrin till två platser.
Anmärkning
OTLP-exportören visas bara för att underlätta. Vi stöder inte officiellt OTLP-exportören eller några komponenter eller tredjepartsupplevelser nedströms av det.
 
- 
              Installera paketet OpenTelemetry.Exporter.OpenTelemetryProtocol i projektet.
    dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
- Lägg till följande kodfragment. Det här exemplet förutsätter att du har en OpenTelemetry Collector med en OTLP-mottagare igång. Mer information finns i exemplet på GitHub.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
    
// Add the OpenTelemetry OTLP exporter to the application.
// This exporter will send telemetry data to an OTLP receiver, such as Prometheus
builder.Services.AddOpenTelemetry().WithTracing(builder => builder.AddOtlpExporter());
builder.Services.AddOpenTelemetry().WithMetrics(builder => builder.AddOtlpExporter());
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
- 
              Installera paketet OpenTelemetry.Exporter.OpenTelemetryProtocol i projektet.
    dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
- Lägg till följande kodfragment. Det här exemplet förutsätter att du har en OpenTelemetry Collector med en OTLP-mottagare igång. Mer information finns i exemplet på GitHub.
    // Create a new OpenTelemetry tracer provider and add the Azure Monitor trace exporter and the OTLP trace exporter.
    // It is important to keep the TracerProvider instance active throughout the process lifetime.
    var tracerProvider = Sdk.CreateTracerProviderBuilder()
        .AddAzureMonitorTraceExporter()
        .AddOtlpExporter()
        .Build();
    // Create a new OpenTelemetry meter provider and add the Azure Monitor metric exporter and the OTLP metric exporter.
    // It is important to keep the MetricsProvider instance active throughout the process lifetime.
    var metricsProvider = Sdk.CreateMeterProviderBuilder()
        .AddAzureMonitorMetricExporter()
        .AddOtlpExporter()
        .Build();
Du kan inte aktivera exportör av OpenTelemetry Protocol (OTLP) tillsammans med Azure Monitor Exporter för att skicka telemetrin till två platser.
- 
              Installera OpenTelemetry Collector Trace Exporter och andra OpenTelemetry-paket i projektet.
npm install @opentelemetry/api
npm install @opentelemetry/exporter-trace-otlp-http
npm install @opentelemetry/sdk-trace-base
npm install @opentelemetry/sdk-trace-node
- Lägg till följande kodfragment. Det här exemplet förutsätter att du har en OpenTelemetry Collector med en OTLP-mottagare igång. Mer information finns i exemplet på GitHub.
export class OtlpExporterSample {
  static async run() {
    const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
    const { BatchSpanProcessor } = await import("@opentelemetry/sdk-trace-base");
    const { OTLPTraceExporter } = await import("@opentelemetry/exporter-trace-otlp-http");
    // Create an OTLP trace exporter (set 'url' if your collector isn't on the default endpoint).
    const otlpExporter = new OTLPTraceExporter({
      // url: "http://localhost:4318/v1/traces",
    });
    // Configure Azure Monitor and add the OTLP exporter as an additional span processor.
    const options = {
      azureMonitorExporterOptions: {
        connectionString:
          process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
      },
      spanProcessors: [new BatchSpanProcessor(otlpExporter)],
    };
    const monitor = useAzureMonitor(options);
    console.log("Azure Monitor initialized (OTLP exporter added)");
  }
}
- 
              Installera opentelemetry-exporter-otlp-paketet. 
- Lägg till följande kodfragment. Det här exemplet förutsätter att du har en OpenTelemetry Collector med en OTLP-mottagare igång. Mer information finns i denna README. 
    # Import the `configure_azure_monitor()`, `trace`, `OTLPSpanExporter`, and `BatchSpanProcessor` classes from the appropriate packages.    
    from azure.monitor.opentelemetry import configure_azure_monitor
    from opentelemetry import trace
    from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
    from opentelemetry.sdk.trace.export import BatchSpanProcessor
    # 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>",
    )
    
    # Get the tracer for the current module.
    tracer = trace.get_tracer(__name__) 
    
    # Create an OTLP span exporter that sends spans to the specified endpoint.
    # Replace `http://localhost:4317` with the endpoint of your OTLP collector.
    otlp_exporter = OTLPSpanExporter(endpoint="http://localhost:4317")
    
    # Create a batch span processor that uses the OTLP span exporter.
    span_processor = BatchSpanProcessor(otlp_exporter)
    
    # Add the batch span processor to the tracer provider.
    trace.get_tracer_provider().add_span_processor(span_processor)
    
    # Start a new span with the name "test".
    with tracer.start_as_current_span("test"):
        print("Hello world!")
 
OpenTelemetry-konfigurationer
Följande OpenTelemetry-konfigurationer kan nås via miljövariabler när du använder Azure Monitor OpenTelemetry Distros.
| Miljövariabel | beskrivning | 
| APPLICATIONINSIGHTS_CONNECTION_STRING | Ange den till anslutningssträngen för Application Insights-resursen. | 
| APPLICATIONINSIGHTS_STATSBEAT_DISABLED | Ställ in den på trueom du vill avregistrera dig från intern måttsamling. | 
| OTEL_RESOURCE_ATTRIBUTES | Nyckel/värde-par som ska användas som resursattribut. Mer information om resursattribut finns i Resource SDK-specifikationen. | 
| OTEL_SERVICE_NAME | Anger värdet för resursattributet service.name. Omservice.nameockså anges iOTEL_RESOURCE_ATTRIBUTES, så harOTEL_SERVICE_NAMEföreträde. | 
| Miljövariabel | beskrivning | 
| APPLICATIONINSIGHTS_CONNECTION_STRING | Ange den till anslutningssträngen för Application Insights-resursen. | 
| APPLICATIONINSIGHTS_STATSBEAT_DISABLED | Ställ in den på trueom du vill avregistrera dig från intern måttsamling. | 
| OTEL_RESOURCE_ATTRIBUTES | Nyckel/värde-par som ska användas som resursattribut. Mer information om resursattribut finns i Resource SDK-specifikationen. | 
| OTEL_SERVICE_NAME | Anger värdet för resursattributet service.name. Omservice.nameockså anges iOTEL_RESOURCE_ATTRIBUTES, så harOTEL_SERVICE_NAMEföreträde. | 
Mer information om Java finns i tilläggsdokumentationen för Java.
Mer information om OpenTelemetry SDK-konfiguration finns i dokumentationen om OpenTelemetry.
 
Redigera URL-frågesträngar
Om du vill redigera URL-frågesträngar inaktiverar du frågesträngssamlingen. Vi rekommenderar den här inställningen om du anropar Azure Storage med en SAS-token.
När du använder distributionspaketet Azure.Monitor.OpenTelemetry.AspNetCore ingår både biblioteken ASP.NET Core och HttpClient Instrumentation.
Vårt distributionspaket har frågesträngsredigering avstängd som standard.
Om du vill ändra det här beteendet måste du ange en miljövariabel till antingen true eller false.
- ASP.NET Core Instrumentation: OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTIONFrågesträngsredigering är inaktiverad som standard. Om du vill aktivera anger du den här miljövariabeln tillfalse.
- Http-klientinstrumentation: OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTIONFrågesträngsredigering är inaktiverad som standard. Om du vill aktivera anger du den här miljövariabeln tillfalse.
När du använder Azure.Monitor.OpenTelemetry.Exporter måste du manuellt inkludera biblioteken ASP.NET Core eller HttpClient Instrumentation i din OpenTelemetry-konfiguration.
Dessa instrumentationsbibliotek har QueryString Redaction aktiverat som standard.
Om du vill ändra det här beteendet måste du ange en miljövariabel till antingen true eller false.
- ASP.NET Core Instrumentation: OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTIONFrågesträngsredigering är aktiverat som standard. Om du vill inaktivera anger du miljövariabeln tilltrue.
- Http-klientinstrumentation: OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTIONFrågesträngsredigering är aktiverat som standard. Om du vill inaktivera anger du miljövariabeln tilltrue.
Lägg till följande i konfigurationsfilen applicationinsights.json :
{
  "preview": {
    "processors": [
      {
        "type": "attribute",
        "actions": [
          {
            "key": "url.query",
            "pattern": "^.*$",
            "replace": "REDACTED",
            "action": "mask"
          }
        ]
      },
      {
        "type": "attribute",
        "actions": [
          {
            "key": "url.full",
            "pattern": "[?].*$",
            "replace": "?REDACTED",
            "action": "mask"
          }
        ]
      }
    ]
  }
}
Vi arbetar aktivt i OpenTelemetry-communityn för att stödja redigering.
När du använder Azure Monitor OpenTelemetry-distributionspaketet kan frågesträngar redigeras genom att skapa och tillämpa en span-processor på distributionskonfigurationen.
export class RedactQueryStringsSample {
  static async run() {
    const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
    const { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET, SEMATTRS_HTTP_URL } =
      await import("@opentelemetry/semantic-conventions");
    class RedactQueryStringProcessor {
      forceFlush() { return Promise.resolve(); }
      onStart() {}
      shutdown() { return Promise.resolve(); }
      onEnd(span: any) {
        const route = String(span.attributes[SEMATTRS_HTTP_ROUTE] ?? "");
        const url = String(span.attributes[SEMATTRS_HTTP_URL] ?? "");
        const target = String(span.attributes[SEMATTRS_HTTP_TARGET] ?? "");
        const strip = (s: string) => {
          const i = s.indexOf("?");
          return i === -1 ? s : s.substring(0, i);
        };
        if (route) span.attributes[SEMATTRS_HTTP_ROUTE] = strip(route);
        if (url) span.attributes[SEMATTRS_HTTP_URL] = strip(url);
        if (target) span.attributes[SEMATTRS_HTTP_TARGET] = strip(target);
      }
    }
    const options = {
      azureMonitorExporterOptions: {
        connectionString:
          process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
      },
      spanProcessors: [new RedactQueryStringProcessor()],
    };
    const monitor = useAzureMonitor(options);
    console.log("Azure Monitor initialized (query strings redacted)");
  }
}
Vi arbetar aktivt i OpenTelemetry-communityn för att stödja redigering.
 
Måttexportintervall
Du kan konfigurera måttexportintervallet med hjälp av OTEL_METRIC_EXPORT_INTERVAL miljövariabeln.
OTEL_METRIC_EXPORT_INTERVAL=60000
Standardvärdet är 60000 millisekunder (60 sekunder). Den här inställningen styr hur ofta OpenTelemetry SDK exporterar mått.
Tips
Azure Monitor Metrics och Azure Monitor Workspace matar in anpassade mått med ett fast intervall på 60 sekunder. Mått som skickas oftare är buffrade och bearbetas en gång varje 60:e sekund. Log Analytics registrerar mått med det intervall som de skickas, vilket kan öka kostnaden med kortare intervall och fördröja synligheten vid längre.
 
Mer information finns i följande OpenTelemetry-specifikationer: