Skip to content

Commit 44270b3

Browse files
authored
Merge pull request #9 from ks6088ts-labs/feature/issue-8_update-otel
add otel metrics feature
2 parents d19907d + a898328 commit 44270b3

File tree

5 files changed

+52
-10
lines changed

5 files changed

+52
-10
lines changed

docs/index.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
## Azure Functions
88

9+
- [Azure Functions で OpenTelemetry を使用する](https://learn.microsoft.com/ja-jp/azure/azure-functions/opentelemetry-howto?tabs=app-insights&pivots=programming-language-python)
910
- [Using FastAPI Framework with Azure Functions](https://learn.microsoft.com/en-us/samples/azure-samples/fastapi-on-azure-functions/fastapi-on-azure-functions/)
1011
- [ks6088ts-labs/azure-functions-python](https://github.com/ks6088ts-labs/azure-functions-python)
1112

@@ -19,7 +20,12 @@
1920
## Application Insights
2021

2122
- [Application Insights の概要 - OpenTelemetry の可観測性](https://learn.microsoft.com/ja-jp/azure/azure-monitor/app/app-insights-overview)
23+
- [Azure Monitor OpenTelemetry を設定する](https://learn.microsoft.com/ja-jp/azure/azure-monitor/app/opentelemetry-configuration?tabs=python)
2224
- [open-telemetry/opentelemetry-python > Basic Trace](https://github.com/open-telemetry/opentelemetry-python/tree/main/docs/examples/basic_tracer)
2325
- [FastAPI のテレメトリデータを Azure Application Insights に送る](https://qiita.com/hoto17296/items/2f366dfabdbe3d1d4e97)
2426
- [【Azure Functions】 - Application Insights のログが表示されない問題](https://zenn.dev/headwaters/articles/ff19f7e1b99b44)
2527
- [opentelemetry-instrumentation-fastapi (python) から OpenTelemetry に入門する](https://zenn.dev/taxin/articles/opentelemetry-fast-api-instrumentation-basics)
28+
29+
## OpenTelemetry
30+
31+
- [Docs > Language APIs & SDKs > Python > Getting Started](https://opentelemetry.io/docs/languages/python/getting-started/)

host.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
{
22
"version": "2.0",
3+
"telemetryMode": "OpenTelemetry",
34
"extensions": {
45
"http": {
56
"routePrefix": ""

local.settings.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
"IsEncrypted": false,
33
"Values": {
44
"APPLICATIONINSIGHTS_CONNECTION_STRING": "InstrumentationKey=YOUR_INSTRUMENTATION_KEY;IngestionEndpoint=https://japaneast-1.in.applicationinsights.azure.com/;LiveEndpoint=https://japaneast.livediagnostics.monitor.azure.com/;ApplicationId=YOUR_APPLICATION_ID",
5+
"OTEL_RESOURCE_ATTRIBUTES": "service.namespace=my-namespace,service.instance.id=my-instance",
6+
"OTEL_SERVICE_NAME": "my-helloworld-service",
7+
"OTEL_TRACES_SAMPLER_ARG": "1",
58
"FUNCTIONS_WORKER_RUNTIME": "python",
69
"AzureWebJobsFeatureFlags": "EnableWorkerIndexing",
710
"AzureWebJobsStorage": ""

template_fastapi/app.py

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,20 +9,14 @@
99

1010
from azure.monitor.opentelemetry import configure_azure_monitor
1111
from fastapi import FastAPI, HTTPException, Query
12-
from opentelemetry import trace
1312
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
14-
from opentelemetry.sdk.trace import TracerProvider
15-
from opentelemetry.sdk.trace.export import (
16-
BatchSpanProcessor,
17-
ConsoleSpanExporter,
18-
)
1913
from opentelemetry.trace import Span
2014
from pydantic import BaseModel
2115

22-
trace.set_tracer_provider(TracerProvider())
23-
trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
24-
tracer = trace.get_tracer(__name__)
16+
from template_fastapi.opentelemetry import get_meter, get_tracer
2517

18+
tracer = get_tracer(__name__)
19+
meter = get_meter(__name__)
2620
app = FastAPI()
2721

2822
# If APPLICATIONINSIGHTS_CONNECTION_STRING exists, configure Azure Monitor
@@ -40,6 +34,7 @@ def server_request_hook(span: Span, scope: dict):
4034

4135
configure_azure_monitor(
4236
connection_string=AZURE_CONNECTION_STRING,
37+
# enable_live_metrics=True,
4338
server_request_hook=server_request_hook,
4439
)
4540
FastAPIInstrumentor.instrument_app(app)
@@ -188,6 +183,7 @@ async def flaky(failure_rate: int):
188183

189184

190185
# Add flaky API which raises an exception
186+
@tracer.start_as_current_span("flaky_exception")
191187
@app.get("/flaky/exception", tags=["flaky"], operation_id="flaky_exception")
192188
async def flaky_exception():
193189
"""
@@ -215,9 +211,29 @@ async def heavy_sync_with_sleep(sleep_ms: int):
215211

216212
import time
217213

218-
with tracer.start_as_current_span("foo"):
214+
with tracer.start_as_current_span("parent"):
219215
print(f"Sleeping for {sleep_ms} milliseconds")
220216
time.sleep(sleep_ms / 1000.0)
217+
with tracer.start_as_current_span("child"):
218+
print("Child span")
221219
return {
222220
"message": f"Slept for {sleep_ms} milliseconds",
223221
}
222+
223+
224+
# Add counter for dice rolls
225+
roll_counter = meter.create_counter(
226+
"dice.rolls",
227+
description="The number of rolls by roll value",
228+
)
229+
230+
231+
@app.get("/roll_dice", operation_id="roll_dice")
232+
async def roll_dice():
233+
"""
234+
Simulate rolling a dice and record the roll in the meter.
235+
"""
236+
with tracer.start_as_current_span("roll_dice"):
237+
roll = random.randint(1, 6)
238+
roll_counter.add(1, {"roll.value": str(roll)})
239+
return roll

template_fastapi/opentelemetry.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from opentelemetry import metrics, trace
2+
from opentelemetry.sdk.trace import TracerProvider
3+
from opentelemetry.sdk.trace.export import (
4+
BatchSpanProcessor,
5+
ConsoleSpanExporter,
6+
)
7+
8+
9+
def get_tracer(name: str):
10+
trace.set_tracer_provider(TracerProvider())
11+
trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
12+
return trace.get_tracer(name)
13+
14+
15+
def get_meter(name: str):
16+
return metrics.get_meter(name)

0 commit comments

Comments
 (0)