### Start Tilt for Logfire Setup Source: https://docs.pydantic.dev/logfire/reference/self-hosted/local-quickstart/index Command to start Tilt, which will automate the deployment of Logfire and its dependencies. Requires setting environment variables for email and key path. ```bash LOGFIRE_EMAIL= \ LOGFIRE_KEY_PATH="$(pwd)/key.json" \ LOGFIRE_ADMIN_EMAIL= \ tilt up ``` -------------------------------- ### Example values.yaml for Logfire Helm Chart Source: https://docs.pydantic.dev/logfire/reference/self-hosted/installation/index This is a comprehensive example of a `values.yaml` file for the logfire Helm chart. It includes configurations for admin email, image pull secrets, PostgreSQL databases (for core and Dex), Dex identity provider settings (including GitHub connector), object storage (S3), and ingress. This serves as a starting point for deploying Logfire. ```yaml adminEmail: admin-email@my-company.dev # Configure the Image Pull Secrets imagePullSecrets: - logfire-image-key # Configure Logfire Postgres Databases postgresDsn: postgres://postgres:postgres@postgres.example.com:5432/crud postgresFFDsn: postgres://postgres:postgres@postgres.example.com:5432/ff # Configure Dex Postgres & Identity Provider logfire-dex: config: storage: type: postgres config: host: postgres.example.com port: 5432 user: postgres database: dex password: postgres ssl: mode: disable connectors: - type: "github" id: "github" name: "GitHub" config: clientID: client_id clientSecret: client_secret getUserInfo: true # Configure Object Storage objectStore: uri: s3://logfire-example-bucket env: AWS_ACCESS_KEY_ID: logfire-example AWS_SECRET_ACCESS_KEY: logfire-example # Configure Ingress ingress: enabled: true tls: true hostnames: - logfire.example.com ingressClassName: nginx ``` -------------------------------- ### Configure Logfire Setup with Tilt Source: https://docs.pydantic.dev/logfire/reference/self-hosted/local-quickstart/index This Tiltfile automates the Logfire setup for local development. It loads necessary extensions, configures Kubernetes resources, and sets up Helm repositories and resources. It requires environment variables for authentication and email. ```python load('ext://secret', 'secret_yaml_registry') load('ext://helm_resource', 'helm_resource', 'helm_repo') update_settings ( max_parallel_updates = 3 , k8s_upsert_timeout_secs = 600 , suppress_unused_image_warnings = None ) k8s_yaml(secret_yaml_registry("logfire-image-key", flags_dict = { 'docker-server': 'us-docker.pkg.dev', 'docker-username': '_json_key', 'docker-email': os.getenv('LOGFIRE_EMAIL'), 'docker-password': read_file(os.getenv('LOGFIRE_KEY_PATH')) })) helm_repo('pydantic', 'https://charts.pydantic.dev/') helm_resource('logfire', 'pydantic/logfire', flags=[ '--set=adminEmail=' + os.getenv('LOGFIRE_ADMIN_EMAIL'), '--set=imagePullSecrets[0]=logfire-image-key', '--set=dev.deployPostgres=true', '--set=dev.deployMinio=true', '--set=dev.deployMaildev=true', '--set=objectStore.uri=s3://logfire', '--set=objectStore.env.AWS_ACCESS_KEY_ID=logfire-minio', '--set=objectStore.env.AWS_SECRET_ACCESS_KEY=logfire-minio', '--set=objectStore.env.AWS_ENDPOINT=http://logfire-minio:9000', '--set=objectStore.env.AWS_ALLOW_HTTP=true', '--set="ingress.hostnames[0]=localhost:8080"', ], links=[link('http://localhost:1080', 'maildev')], ) k8s_resource( workload='logfire', port_forwards=[ port_forward(8080, 8080, name='logfire'), ], extra_pod_selectors=[ {'app.kubernetes.io/component': 'logfire-service'}, ], discovery_strategy='selectors-only', ) local_resource( 'maildev-portforward', serve_cmd='kubectl port-forward svc/logfire-maildev 1080:1080', deps=['logfire'], allow_parallel=True, ) ``` -------------------------------- ### Setup PostgreSQL Database using Docker Source: https://docs.pydantic.dev/logfire/integrations/databases/asyncpg/index Starts a PostgreSQL database instance using Docker. This command configures the user, password, database name, and exposes the default PostgreSQL port. ```bash docker run --name postgres \ -e POSTGRES_USER=user \ -e POSTGRES_PASSWORD=secret \ -e POSTGRES_DB=database \ -p 5432:5432 \ -d postgres ``` -------------------------------- ### Configure Object Storage with Amazon S3 Source: https://docs.pydantic.dev/logfire/reference/self-hosted/installation/index This example shows how to configure object storage using Amazon S3. It specifies the S3 URI and demonstrates how to provide AWS credentials either directly or by referencing a Kubernetes secret for sensitive values like `AWS_SECRET_ACCESS_KEY`. ```yaml objectStore: uri: s3:// env: AWS_DEFAULT_REGION: AWS_SECRET_ACCESS_KEY: valueFrom: secretKeyRef: name: my-aws-secret key: secret-key AWS_ACCESS_KEY_ID: ``` -------------------------------- ### Install Logfire in Development Mode with Helm Source: https://docs.pydantic.dev/logfire/reference/self-hosted/local-quickstart/index This Helm command installs Logfire using the 'pydantic/logfire' chart in development mode. It configures essential services like PostgreSQL, Minio, and Maildev, sets up object storage, and defines ingress hostnames. Note that these development services are not production-ready. ```bash helm install logfire pydantic/logfire \ --set=adminEmail=my-awesome-email@example.com \ --set="imagePullSecrets[0]=logfire-image-key" \ --set=dev.deployPostgres=true \ --set=dev.deployMinio=true \ --set=dev.deployMaildev=true \ --set=objectStore.uri=s3://logfire \ --set=objectStore.env.AWS_ACCESS_KEY_ID=logfire-minio \ --set=objectStore.env.AWS_SECRET_ACCESS_KEY=logfire-minio \ --set=objectStore.env.AWS_ENDPOINT=http://logfire-minio:9000 \ --set=objectStore.env.AWS_ALLOW_HTTP=true \ --set="ingress.hostnames[0]=localhost:8080" ``` -------------------------------- ### Logfire Setup and OpenAI Instrumentation (Python) Source: https://docs.pydantic.dev/logfire/comparisons/arize-phoenix/index Demonstrates the minimal setup required for Logfire to start observing AI calls, specifically integrating with OpenAI. This highlights Logfire's ease of use and developer experience. ```python import logfire logfire.configure() logfire.instrument_openai() ``` -------------------------------- ### Install Logfire SDK with Datasets Extra Source: https://docs.pydantic.dev/logfire/evaluate/datasets/sdk/index Installs the Logfire SDK with the necessary 'datasets' extra, which includes 'httpx' and 'pydantic-evals' as dependencies. Requires Python 3.10+. ```bash pip install 'logfire[datasets]' ``` -------------------------------- ### Basic Python Logging with Logfire (Development) Source: https://docs.pydantic.dev/logfire/index Demonstrates basic logging in a Python application using Pydantic Logfire. It initializes Logfire with `configure()` and logs an informational message. This setup is recommended for development environments. ```python import logfire logfire.configure() # (1)! logfire.info('Hello, {name}!', name='world') # (2)! ``` -------------------------------- ### Python SDK Installation and Configuration Source: https://docs.pydantic.dev/logfire/ai-observability/index This Python code snippet shows how to install the Logfire SDK using pip and then configure and instrument it within an application. It includes basic configuration and instrumentation for OpenAI, demonstrating the initial setup for using Logfire. ```python import logfire logfire.configure() logfire.instrument_openai() # Or your framework of choice ``` -------------------------------- ### Map Dex Connector Config to Helm Values Source: https://docs.pydantic.dev/logfire/reference/self-hosted/installation/index Demonstrates how to map a Dex identity provider connector configuration from its documentation format to the structure expected within the Logfire Helm `values.yaml` file. ```yaml logfire-dex: config: connectors: - type: "github" id: "github" name: "GitHub" config: ... ``` -------------------------------- ### List and Get Datasets with Logfire SDK Source: https://docs.pydantic.dev/logfire/evaluate/datasets/sdk/index This snippet demonstrates how to list all datasets available in the Logfire project and retrieve details for a specific dataset. It requires an initialized Logfire client object. ```python # List all datasets in the project datasets = client.list_datasets() for ds in datasets: print(f"{ds['name']}: {ds['case_count']} cases") # Get a specific dataset by name or ID dataset_info = client.get_dataset('qa-golden-set') ``` -------------------------------- ### Install Logfire SDK using uv Source: https://docs.pydantic.dev/logfire/index Installs the Pydantic Logfire SDK using uv, a fast Python package installer and resolver. This is an alternative to pip for managing Python dependencies. ```bash uv add logfire ``` -------------------------------- ### Install Logfire SDK using pip Source: https://docs.pydantic.dev/logfire/index Installs the Pydantic Logfire SDK using pip, a common package installer for Python. This is the first step to integrating Logfire into your Python project. ```bash pip install logfire ``` -------------------------------- ### Start Gunicorn with configuration file (Bash) Source: https://docs.pydantic.dev/logfire/integrations/web-frameworks/gunicorn/index This command demonstrates how to start the Gunicorn server using a specified configuration file. Replace `myapp:app` with your WSGI application and `gunicorn_config.py` with the name of your configuration file. ```bash gunicorn myapp:app --config gunicorn_config.py ``` -------------------------------- ### Install Logfire SDK using conda Source: https://docs.pydantic.dev/logfire/index Installs the Pydantic Logfire SDK using conda, a package and environment management system. This is suitable for users within the Anaconda ecosystem. ```bash conda install -c conda-forge logfire ``` -------------------------------- ### Create Local Kubernetes Cluster with Kind Source: https://docs.pydantic.dev/logfire/reference/self-hosted/local-quickstart/index This command initializes a local Kubernetes cluster using the Kind (Kubernetes in Docker) tool. It's a prerequisite for deploying Logfire locally. ```bash kind create cluster ``` -------------------------------- ### Configure Nginx Ingress for Logfire Source: https://docs.pydantic.dev/logfire/reference/self-hosted/installation/index Example configuration for enabling and setting up Nginx Ingress for Logfire. It specifies hostnames, TLS enablement, and annotations for cert-manager to manage SSL certificates. ```yaml ingress: enabled: true tls: true hostnames: - logfire.example.com ingressClassName: nginx annotations: cert-manager.io/cluster-issuer: "letsencrypt" ``` -------------------------------- ### Setup MySQL Database with Docker Source: https://docs.pydantic.dev/logfire/integrations/databases/mysql/index Launches a MySQL database instance using Docker. This command sets up the database with a root password, database name, user, and password, and exposes the default MySQL port. ```bash docker run --name mysql \ -e MYSQL_ROOT_PASSWORD=secret \ -e MYSQL_DATABASE=database \ -e MYSQL_USER=user \ -e MYSQL_PASSWORD=secret \ -p 3306:3306 \ -d mysql ``` -------------------------------- ### Configure Kubernetes Gateway API for Logfire Source: https://docs.pydantic.dev/logfire/reference/self-hosted/installation/index Example configuration for using the Kubernetes Gateway API to expose Logfire. This disables the Ingress resource and enables the Gateway resource with specified class, hostnames, and TLS settings. ```yaml ingress: # Disable the Ingress resource enabled: false # Still required for CORS headers and Gateway listener hostname tls: true hostnames: - logfire.example.com # TLS secret for the Gateway listener secretName: logfire-tls-cert gateway: enabled: true # Create the Gateway resource (default: true) create: true # GatewayClass name (required when create is true) # Common values: istio, cilium, nginx, envoy-gateway, gke-l7-rilb gatewayClassName: istio # Custom Gateway name (optional, defaults to "logfire-gateway") name: logfire-gateway ``` -------------------------------- ### Install and Run FastAPI App with Logfire Source: https://docs.pydantic.dev/logfire/why/index This bash snippet provides the commands to install the necessary packages for a Logfire-instrumented FastAPI application and to run the application using uvicorn. It requires `logfire[fastapi]`, `fastapi`, and `uvicorn`. ```bash pip install 'logfire[fastapi]' fastapi uvicorn # (1)! uvicorn main:app # (2)! ``` -------------------------------- ### Create Kubernetes Cluster with Kind Source: https://docs.pydantic.dev/logfire/reference/self-hosted/local-quickstart/index Command to create a local Kubernetes cluster using Kind. This is a prerequisite for running Logfire locally with Tilt. ```bash kind create cluster ``` -------------------------------- ### Customizing Span Message After Span Start (Python) Source: https://docs.pydantic.dev/logfire/guides/onboarding-checklist/add-manual-tracing/index Shows how to set or modify the `span.message` after a span has been started but before it finishes. This allows for dynamic message content based on intermediate calculations or states within the span. ```python with logfire.span('Calculating...') as span: result = 1 + 2 span.message = f'Calculated: {result}' ``` -------------------------------- ### Install OpenFeature React SDK (yarn) Source: https://docs.pydantic.dev/logfire/how-to-guides/client-side-feature-flags/index Installs the OpenFeature React SDK using yarn. This is the command for projects that utilize yarn as their package manager. ```bash yarn add @openfeature/react-sdk ``` -------------------------------- ### Stripe Client Initialization and Request Examples (Python) Source: https://docs.pydantic.dev/logfire/integrations/stripe/index Demonstrates how to initialize the Stripe Python client and make both synchronous and asynchronous requests. It highlights the default HTTP clients used by the Stripe library. ```python from stripe import StripeClient client = StripeClient(api_key='') # Synchronous request client.customers.list() # uses `requests` # Asynchronous request async def main(): await client.customers.list_async() # uses `httpx` if __name__ == '__main__': import asyncio asyncio.run(main()) ``` -------------------------------- ### Logfire CLI Authentication Source: https://docs.pydantic.dev/logfire/index Authenticates the local environment with Logfire. Upon successful authentication, credentials are stored in `~/.logfire/default.toml`. ```bash logfire auth ``` -------------------------------- ### Setup PostgreSQL Database with Docker Source: https://docs.pydantic.dev/logfire/integrations/databases/psycopg/index Launches a PostgreSQL database instance using Docker. This command sets up a database named 'database' with user 'user' and password 'secret', accessible on port 5432. ```bash docker run --rm --name postgres \ -e POSTGRES_USER=user \ -e POSTGRES_PASSWORD=secret \ -e POSTGRES_DB=database \ -p 5432:5432 \ -d postgres ``` -------------------------------- ### Start New Trace for Background Task Spans (Python) Source: https://docs.pydantic.dev/logfire/how-to-guides/sampling/index Provides a workaround for the issue where spans from background tasks might be included while the root span is discarded. This example uses `logfire.attach_context({})` to ensure that spans within the `with` block start a new, independent trace. ```python import asyncio import logfire async def background_task(): # `attach_context({})` forgets existing context # so that spans within start a new trace. with logfire.attach_context({}): with logfire.span('new trace'): await asyncio.sleep(0.2) logfire.info('background') ``` -------------------------------- ### Async Logfire Query Client Examples Source: https://docs.pydantic.dev/logfire/how-to-guides/query-api/index Demonstrates asynchronous querying using `AsyncLogfireQueryClient`. It shows how to fetch data in JSON (column and row oriented), Arrow, and CSV formats, and how to integrate with Polars DataFrames. Also includes fetching read token information. ```python from io import StringIO import polars as pl from logfire.query_client import AsyncLogfireQueryClient async def main(): query = """ SELECT start_timestamp FROM records LIMIT 1 """ async with AsyncLogfireQueryClient(read_token='') as client: # Load data as JSON, in column-oriented format json_cols = await client.query_json(sql=query) print(json_cols) # Load data as JSON, in row-oriented format json_rows = await client.query_json_rows(sql=query) print(json_rows) # Retrieve data in arrow format, and load into a polars DataFrame # Note that JSON columns such as `attributes` will be returned as # JSON-serialized strings df_from_arrow = pl.from_arrow(await client.query_arrow(sql=query)) print(df_from_arrow) # Retrieve data in CSV format, and load into a polars DataFrame # Note that JSON columns such as `attributes` will be returned as # JSON-serialized strings df_from_csv = pl.read_csv(StringIO(await client.query_csv(sql=query))) print(df_from_csv) # Get read token info read_token_info = await client.info() print(read_token_info) if __name__ == '__main__': import asyncio asyncio.run(main()) ``` -------------------------------- ### Logfire CLI Help Source: https://docs.pydantic.dev/logfire/index Displays the help information for the Logfire CLI tool. This command is useful for understanding available subcommands and options. ```bash logfire -h ``` -------------------------------- ### Install OpenFeature React SDK (pnpm) Source: https://docs.pydantic.dev/logfire/how-to-guides/client-side-feature-flags/index Installs the OpenFeature React SDK using pnpm. This command is used for projects that manage dependencies with pnpm. ```bash pnpm add @openfeature/react-sdk ``` -------------------------------- ### Create Logfire API Client Source: https://docs.pydantic.dev/logfire/evaluate/datasets/sdk/index Demonstrates how to instantiate a synchronous LogfireAPIClient with an API key. The client can also be used as a context manager for proper resource management. An optional 'base_url' can be provided for self-hosted instances. ```python from logfire.experimental.api_client import LogfireAPIClient client = LogfireAPIClient(api_key='your-api-key') with LogfireAPIClient(api_key='your-api-key') as client: ... client = LogfireAPIClient( api_key='your-api-key', base_url='http://localhost:8000', ) ``` -------------------------------- ### Logfire CLI Set Project Source: https://docs.pydantic.dev/logfire/index Sets the active Logfire project for the current directory. This command should be run from the root of your application. Replace `` with your actual project name. ```bash logfire projects use ``` -------------------------------- ### Synchronous Logfire Query Client Examples Source: https://docs.pydantic.dev/logfire/how-to-guides/query-api/index Demonstrates synchronous querying using `LogfireQueryClient`. It mirrors the asynchronous example, showing how to fetch data in JSON (column and row oriented), Arrow, and CSV formats, and integrate with Polars. It also includes fetching read token information. ```python from io import StringIO import polars as pl from logfire.query_client import LogfireQueryClient def main(): query = """ SELECT start_timestamp FROM records LIMIT 1 """ with LogfireQueryClient(read_token='') as client: # Load data as JSON, in column-oriented format json_cols = client.query_json(sql=query) print(json_cols) # Load data as JSON, in row-oriented format json_rows = client.query_json_rows(sql=query) print(json_rows) # Retrieve data in arrow format, and load into a polars DataFrame # Note that JSON columns such as `attributes` will be returned as # JSON-serialized strings df_from_arrow = pl.from_arrow(client.query_arrow(sql=query)) print(df_from_arrow) # Retrieve data in CSV format, and load into a polars DataFrame # Note that JSON columns such as `attributes` will be returned as # JSON-serialized strings df_from_csv = pl.read_csv(StringIO(client.query_csv(sql=query))) print(df_from_csv) # Get read token info read_token_info = client.info() print(read_token_info) if __name__ == '__main__': main() ``` -------------------------------- ### Add Logfire Helm Repository Source: https://docs.pydantic.dev/logfire/reference/self-hosted/installation/index This command adds the official Logfire Helm chart repository to your local Helm configuration. This is a prerequisite for deploying the Logfire Helm chart. ```bash helm repo add pydantic https://charts.pydantic.dev/ ``` -------------------------------- ### Basic Logfire Instrumentation in Python Source: https://docs.pydantic.dev/logfire/faq/index This snippet demonstrates the minimal code required to set up Logfire for basic instrumentation in a Python application. It imports the logfire library and calls configuration and instrumentation functions. ```python import logfire logfire.configure() logfire.instrument_pydantic_ai() # Or your framework of choice ``` -------------------------------- ### Make Direct HTTP GET Request to Logfire API using Python requests Source: https://docs.pydantic.dev/logfire/how-to-guides/query-api/index An example using the Python `requests` library to make a direct HTTP GET request to the Logfire API. It demonstrates setting the endpoint URL, authentication headers, defining a SQL query, and sending the request to the `/v1/query` endpoint. ```python import requests # Define the base URL and your read token base_url = 'https://logfire-us.pydantic.dev' # or 'https://logfire-eu.pydantic.dev' for EU accounts read_token = '' # Set the headers for authentication headers = {'Authorization': f'Bearer {read_token}'} # Define your SQL query query = """ SELECT start_timestamp FROM records LIMIT 1 """ # Prepare the query parameters for the GET request params = {'sql': query} # Send the GET request to the Logfire API response = requests.get(f'{base_url}/v1/query', params=params, headers=headers) # Check the response status if response.status_code == 200: print('Query Successful!') print(response.json()) else: print(f'Failed to execute query. Status code: {response.status_code}') print(response.text) ``` -------------------------------- ### Setup Redis Server Using Docker Source: https://docs.pydantic.dev/logfire/integrations/databases/redis/index Starts a Redis server in a Docker container, making it accessible on the default port 6379. This is a prerequisite for running the Python script that uses Redis. ```bash docker run --name redis -p 6379:6379 -d redis:latest ``` -------------------------------- ### Install OpenFeature Web SDK and OFREP Provider (yarn) Source: https://docs.pydantic.dev/logfire/how-to-guides/client-side-feature-flags/index Installs the OpenFeature Web SDK and OFREP provider using the yarn package manager. This command is used for projects managed with yarn. ```bash yarn add @openfeature/web-sdk @openfeature/ofrep-web-provider ``` -------------------------------- ### Example: Text Generation with Tools and Telemetry Source: https://docs.pydantic.dev/logfire/integrations/javascript/vercel-ai/index Demonstrates a complete example of text generation using a tool with telemetry enabled. It includes defining a tool for weather lookup and configuring the AI SDK call with telemetry options. ```typescript import { generateText, tool } from "ai"; import { yourProvider } from "@ai-sdk/your-provider"; import { z } from "zod"; const result = await generateText({ model: yourProvider("model-name"), experimental_telemetry: { isEnabled: true }, tools: { weather: tool({ description: "Get the weather in a location", inputSchema: z.object({ location: z.string().describe("The location to get the weather for"), }), execute: async ({ location }) => ({ location, temperature: 72 + Math.floor(Math.random() * 21) - 10, }), }), }, prompt: "What is the weather in San Francisco?", }); console.log(result.text); ``` -------------------------------- ### Filter Records by Start Timestamp Source: https://docs.pydantic.dev/logfire/reference/sql/index Demonstrates how to filter log records based on their start_timestamp using SQL. This example shows filtering for records within the last 5 minutes. ```sql SELECT * FROM records WHERE start_timestamp >= now() - interval '5 minutes' ``` -------------------------------- ### Create Logfire Kubernetes Namespace Source: https://docs.pydantic.dev/logfire/reference/self-hosted/installation/index This command creates a dedicated Kubernetes namespace named 'logfire' to host all Logfire-related resources. It's good practice to isolate application deployments into their own namespaces. ```bash kubectl create namespace logfire ``` -------------------------------- ### Configure Minimum Log Level for Logfire Source: https://docs.pydantic.dev/logfire/guides/onboarding-checklist/add-manual-tracing/index Demonstrates how to configure logfire to only create logs and spans above a certain minimum level using the `min_level` argument in `logfire.configure`. It also shows how to set a minimum level specifically for console output. ```python import logfire logfire.configure(min_level='info') ``` ```python import logfire logfire.configure(console=logfire.ConsoleOptions(min_log_level='debug')) ``` ```python import logfire logfire.configure(min_level='info') with logfire.span('root') as root: root.set_level('debug') with logfire.span('debug span excluded', _level='debug'): logfire.info('info message') ``` -------------------------------- ### Manually Refresh Agent Configuration Variables Source: https://docs.pydantic.dev/logfire/reference/advanced/managed-variables/configuration-reference/index Provides examples for manually triggering a refresh of agent configuration variables. This includes both synchronous and asynchronous refresh methods, with an option to force an immediate fetch. ```python # Synchronous refresh agent_config.refresh_sync(force=True) # Async refresh await agent_config.refresh(force=True) # The force=True parameter bypasses the polling interval check and fetches the latest configuration immediately. ``` -------------------------------- ### Logfire Initialization and Warning Log Source: https://docs.pydantic.dev/logfire/reference/sql/index This Python snippet demonstrates how to configure Logfire and emit a warning log message with associated data and tags. It's a basic example of how to start logging with the library. ```python import logfire logfire.configure() logfire.warn('beware: {thing}', thing='bad', _tags=['a tag']) ``` -------------------------------- ### Configure Logfire Client in Python Source: https://docs.pydantic.dev/logfire/reference/self-hosted/local-quickstart/index Python code snippet to configure the Logfire client for local use. It sets the base URL to the locally forwarded Logfire service and requires a write token. ```python import logfire logfire.configure( advanced=logfire.AdvancedOptions(base_url='http://localhost:8080'), token='__YOUR_LOGFIRE_WRITE_TOKEN__', ) logfire.info('Hello, {place}!', place='World') ``` -------------------------------- ### Configure NodeJS OpenTelemetry Exporter for Logfire Source: https://docs.pydantic.dev/logfire/how-to-guides/alternative-clients/index This example demonstrates setting up the OpenTelemetry Node.js SDK to export traces to Logfire. It includes installing necessary packages, configuring the exporter with endpoint and headers, and starting/shutting down the SDK. ```javascript import {NodeSDK} from "@opentelemetry/sdk-node"; import {OTLPTraceExporter} from "@opentelemetry/exporter-trace-otlp-proto"; import {BatchSpanProcessor} from "@opentelemetry/sdk-trace-node"; import {trace} from "@opentelemetry/api"; import {Resource} from "@opentelemetry/resources"; import {ATTR_SERVICE_NAME} from "@opentelemetry/semantic-conventions"; const traceExporter = new OTLPTraceExporter(); const spanProcessor = new BatchSpanProcessor(traceExporter); const resource = new Resource({[ATTR_SERVICE_NAME]: "my_service"}); const sdk = new NodeSDK({spanProcessor, resource}); sdk.start(); const tracer = trace.getTracer("my_tracer"); tracer.startSpan("Hello World").end(); sdk.shutdown().catch(console.error); ``` ```shell export OTEL_EXPORTER_OTLP_ENDPOINT=https://logfire-us.pydantic.dev export OTEL_EXPORTER_OTLP_HEADERS='Authorization=your-write-token' npm init es6 -y # creates package.json with type module npm install @opentelemetry/sdk-node node main.js ```