[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-cc6188f7-e2dc-41e8-9056-fef4136fa6a2":3,"$ff4oAz0Pr4egfIvkCLQdX6gRruMCWo4d_g50Li9uieGM":42},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":33},"cc6188f7-e2dc-41e8-9056-fef4136fa6a2","azure-monitor-opentelemetry-ts","自动为Node.js应用程序进行分布式跟踪、指标和日志记录。","cat_coding_backend","mod_coding","sickn33,coding","---\nname: azure-monitor-opentelemetry-ts\ndescription: \"Auto-instrument Node.js applications with distributed tracing, metrics, and logs.\"\nrisk: unknown\nsource: community\ndate_added: \"2026-02-27\"\n---\n\n# Azure Monitor OpenTelemetry SDK for TypeScript\n\nAuto-instrument Node.js applications with distributed tracing, metrics, and logs.\n\n## Installation\n\n```bash\n# Distro (recommended - auto-instrumentation)\nnpm install @azure\u002Fmonitor-opentelemetry\n\n# Low-level exporters (custom OpenTelemetry setup)\nnpm install @azure\u002Fmonitor-opentelemetry-exporter\n\n# Custom logs ingestion\nnpm install @azure\u002Fmonitor-ingestion\n```\n\n## Environment Variables\n\n```bash\nAPPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=...;IngestionEndpoint=...\n```\n\n## Quick Start (Auto-Instrumentation)\n\n**IMPORTANT:** Call `useAzureMonitor()` BEFORE importing other modules.\n\n```typescript\nimport { useAzureMonitor } from \"@azure\u002Fmonitor-opentelemetry\";\n\nuseAzureMonitor({\n  azureMonitorExporterOptions: {\n    connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING\n  }\n});\n\n\u002F\u002F Now import your application\nimport express from \"express\";\nconst app = express();\n```\n\n## ESM Support (Node.js 18.19+)\n\n```bash\nnode --import @azure\u002Fmonitor-opentelemetry\u002Floader .\u002Fdist\u002Findex.js\n```\n\n**package.json:**\n```json\n{\n  \"scripts\": {\n    \"start\": \"node --import @azure\u002Fmonitor-opentelemetry\u002Floader .\u002Fdist\u002Findex.js\"\n  }\n}\n```\n\n## Full Configuration\n\n```typescript\nimport { useAzureMonitor, AzureMonitorOpenTelemetryOptions } from \"@azure\u002Fmonitor-opentelemetry\";\nimport { resourceFromAttributes } from \"@opentelemetry\u002Fresources\";\n\nconst options: AzureMonitorOpenTelemetryOptions = {\n  azureMonitorExporterOptions: {\n    connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING,\n    storageDirectory: \"\u002Fpath\u002Fto\u002Foffline\u002Fstorage\",\n    disableOfflineStorage: false\n  },\n  \n  \u002F\u002F Sampling\n  samplingRatio: 1.0,  \u002F\u002F 0-1, percentage of traces\n  \n  \u002F\u002F Features\n  enableLiveMetrics: true,\n  enableStandardMetrics: true,\n  enablePerformanceCounters: true,\n  \n  \u002F\u002F Instrumentation libraries\n  instrumentationOptions: {\n    azureSdk: { enabled: true },\n    http: { enabled: true },\n    mongoDb: { enabled: true },\n    mySql: { enabled: true },\n    postgreSql: { enabled: true },\n    redis: { enabled: true },\n    bunyan: { enabled: false },\n    winston: { enabled: false }\n  },\n  \n  \u002F\u002F Custom resource\n  resource: resourceFromAttributes({ \"service.name\": \"my-service\" })\n};\n\nuseAzureMonitor(options);\n```\n\n## Custom Traces\n\n```typescript\nimport { trace } from \"@opentelemetry\u002Fapi\";\n\nconst tracer = trace.getTracer(\"my-tracer\");\n\nconst span = tracer.startSpan(\"doWork\");\ntry {\n  span.setAttribute(\"component\", \"worker\");\n  span.setAttribute(\"operation.id\", \"42\");\n  span.addEvent(\"processing started\");\n  \n  \u002F\u002F Your work here\n  \n} catch (error) {\n  span.recordException(error as Error);\n  span.setStatus({ code: 2, message: (error as Error).message });\n} finally {\n  span.end();\n}\n```\n\n## Custom Metrics\n\n```typescript\nimport { metrics } from \"@opentelemetry\u002Fapi\";\n\nconst meter = metrics.getMeter(\"my-meter\");\n\n\u002F\u002F Counter\nconst counter = meter.createCounter(\"requests_total\");\ncounter.add(1, { route: \"\u002Fapi\u002Fusers\", method: \"GET\" });\n\n\u002F\u002F Histogram\nconst histogram = meter.createHistogram(\"request_duration_ms\");\nhistogram.record(150, { route: \"\u002Fapi\u002Fusers\" });\n\n\u002F\u002F Observable Gauge\nconst gauge = meter.createObservableGauge(\"active_connections\");\ngauge.addCallback((result) => {\n  result.observe(getActiveConnections(), { pool: \"main\" });\n});\n```\n\n## Manual Exporter Setup\n\n### Trace Exporter\n\n```typescript\nimport { AzureMonitorTraceExporter } from \"@azure\u002Fmonitor-opentelemetry-exporter\";\nimport { NodeTracerProvider, BatchSpanProcessor } from \"@opentelemetry\u002Fsdk-trace-node\";\n\nconst exporter = new AzureMonitorTraceExporter({\n  connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING\n});\n\nconst provider = new NodeTracerProvider({\n  spanProcessors: [new BatchSpanProcessor(exporter)]\n});\n\nprovider.register();\n```\n\n### Metric Exporter\n\n```typescript\nimport { AzureMonitorMetricExporter } from \"@azure\u002Fmonitor-opentelemetry-exporter\";\nimport { PeriodicExportingMetricReader, MeterProvider } from \"@opentelemetry\u002Fsdk-metrics\";\nimport { metrics } from \"@opentelemetry\u002Fapi\";\n\nconst exporter = new AzureMonitorMetricExporter({\n  connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING\n});\n\nconst meterProvider = new MeterProvider({\n  readers: [new PeriodicExportingMetricReader({ exporter })]\n});\n\nmetrics.setGlobalMeterProvider(meterProvider);\n```\n\n### Log Exporter\n\n```typescript\nimport { AzureMonitorLogExporter } from \"@azure\u002Fmonitor-opentelemetry-exporter\";\nimport { BatchLogRecordProcessor, LoggerProvider } from \"@opentelemetry\u002Fsdk-logs\";\nimport { logs } from \"@opentelemetry\u002Fapi-logs\";\n\nconst exporter = new AzureMonitorLogExporter({\n  connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING\n});\n\nconst loggerProvider = new LoggerProvider();\nloggerProvider.addLogRecordProcessor(new BatchLogRecordProcessor(exporter));\n\nlogs.setGlobalLoggerProvider(loggerProvider);\n```\n\n## Custom Logs Ingestion\n\n```typescript\nimport { DefaultAzureCredential } from \"@azure\u002Fidentity\";\nimport { LogsIngestionClient, isAggregateLogsUploadError } from \"@azure\u002Fmonitor-ingestion\";\n\nconst endpoint = \"https:\u002F\u002F\u003Cdce>.ingest.monitor.azure.com\";\nconst ruleId = \"\u003Cdata-collection-rule-id>\";\nconst streamName = \"Custom-MyTable_CL\";\n\nconst client = new LogsIngestionClient(endpoint, new DefaultAzureCredential());\n\nconst logs = [\n  {\n    Time: new Date().toISOString(),\n    Computer: \"Server1\",\n    Message: \"Application started\",\n    Level: \"Information\"\n  }\n];\n\ntry {\n  await client.upload(ruleId, streamName, logs);\n} catch (error) {\n  if (isAggregateLogsUploadError(error)) {\n    for (const uploadError of error.errors) {\n      console.error(\"Failed logs:\", uploadError.failedLogs);\n    }\n  }\n}\n```\n\n## Custom Span Processor\n\n```typescript\nimport { SpanProcessor, ReadableSpan } from \"@opentelemetry\u002Fsdk-trace-base\";\nimport { Span, Context, SpanKind, TraceFlags } from \"@opentelemetry\u002Fapi\";\nimport { useAzureMonitor } from \"@azure\u002Fmonitor-opentelemetry\";\n\nclass FilteringSpanProcessor implements SpanProcessor {\n  forceFlush(): Promise\u003Cvoid> { return Promise.resolve(); }\n  shutdown(): Promise\u003Cvoid> { return Promise.resolve(); }\n  onStart(span: Span, context: Context): void {}\n  \n  onEnd(span: ReadableSpan): void {\n    \u002F\u002F Add custom attributes\n    span.attributes[\"CustomDimension\"] = \"value\";\n    \n    \u002F\u002F Filter out internal spans\n    if (span.kind === SpanKind.INTERNAL) {\n      span.spanContext().traceFlags = TraceFlags.NONE;\n    }\n  }\n}\n\nuseAzureMonitor({\n  spanProcessors: [new FilteringSpanProcessor()]\n});\n```\n\n## Sampling\n\n```typescript\nimport { ApplicationInsightsSampler } from \"@azure\u002Fmonitor-opentelemetry-exporter\";\nimport { NodeTracerProvider } from \"@opentelemetry\u002Fsdk-trace-node\";\n\n\u002F\u002F Sample 75% of traces\nconst sampler = new ApplicationInsightsSampler(0.75);\n\nconst provider = new NodeTracerProvider({ sampler });\n```\n\n## Shutdown\n\n```typescript\nimport { useAzureMonitor, shutdownAzureMonitor } from \"@azure\u002Fmonitor-opentelemetry\";\n\nuseAzureMonitor();\n\n\u002F\u002F On application shutdown\nprocess.on(\"SIGTERM\", async () => {\n  await shutdownAzureMonitor();\n  process.exit(0);\n});\n```\n\n## Key Types\n\n```typescript\nimport {\n  useAzureMonitor,\n  shutdownAzureMonitor,\n  AzureMonitorOpenTelemetryOptions,\n  InstrumentationOptions\n} from \"@azure\u002Fmonitor-opentelemetry\";\n\nimport {\n  AzureMonitorTraceExporter,\n  AzureMonitorMetricExporter,\n  AzureMonitorLogExporter,\n  ApplicationInsightsSampler,\n  AzureMonitorExporterOptions\n} from \"@azure\u002Fmonitor-opentelemetry-exporter\";\n\nimport {\n  LogsIngestionClient,\n  isAggregateLogsUploadError\n} from \"@azure\u002Fmonitor-ingestion\";\n```\n\n## Best Practices\n\n1. **Call useAzureMonitor() first** - Before importing other modules\n2. **Use ESM loader for ESM projects** - `--import @azure\u002Fmonitor-opentelemetry\u002Floader`\n3. **Enable offline storage** - For reliable telemetry in disconnected scenarios\n4. **Set sampling ratio** - For high-traffic applications\n5. **Add custom dimensions** - Use span processors for enrichment\n6. **Graceful shutdown** - Call `shutdownAzureMonitor()` to flush telemetry\n\n## When to Use\nThis skill is applicable to execute the workflow or actions described in the overview.\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,140,699,"2026-05-16 13:07:17",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":25,"skillCount":32,"createdAt":26},"后端开发","backend","mdi-server","API、数据库、服务端架构",296,[34],{"id":35,"skillId":4,"version":36,"fileName":37,"fileSize":38,"filePath":39,"fileHash":40,"manifest":41,"createdAt":19},"10ac64ef-bc90-4ffd-ac6a-9540e4eaf6e9","1.0.0","azure-monitor-opentelemetry-ts.zip",2952,"uploads\u002Fskills\u002Fcc6188f7-e2dc-41e8-9056-fef4136fa6a2\u002Fazure-monitor-opentelemetry-ts.zip","97f6fffd08310395d0a431ea587234178709d75a83e5c0e4f6b9d17523cff516","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":8643}]",{"code":43,"message":44,"data":45},200,"success",{"items":46,"stats":47,"page":50},[],{"averageRating":48,"totalRatings":48,"ratingCounts":49},0,[48,48,48,48,48],{"limit":51,"offset":48,"hasMore":52,"nextOffset":51,"ratedOnly":16},15,false]