How do I add a Postgres database to the codebase? - open-telemetry/

Adding PostgreSQL to OpenTelemetry

OpenTelemetry is a collection of tools, APIs, and SDKs that you can use to generate, collect, and export telemetry data. To add PostgreSQL as a backend for your OpenTelemetry data, you can use the opentelemetry-postgres exporter.


Before you begin, make sure you have the following:

  • A running PostgreSQL database
  • The opentelemetry-sdk and opentelemetry-postgres packages installed

Installing the opentelemetry-postgres package

To install the opentelemetry-postgres package, you can use your preferred package manager. Here are some examples:

  • npm: npm install @opentelemetry/exporter-postgres
  • yarn: yarn add @opentelemetry/exporter-postgres
  • Go: go get

Configuring the Exporter

To configure the exporter, you need to create a new instance of the PostgresExporter and pass it your OpenTelemetry TracerProvider and MeterProvider. Here's an example in Node.js:

const { NodeTracerProvider } = require('@opentelemetry/api-node');
const { PostgresExporter } = require('@opentelemetry/exporter-postgres');

const tracerProvider = new NodeTracerProvider();
const meterProvider = tracerProvider.getMeterProvider();

const exporter = new PostgresExporter({
  url: 'postgresql://user:password@localhost:5432/database',
  schema: 'my_schema',

tracerProvider.shutdown.then(() => {


Replace user:password@localhost:5432/database with your PostgreSQL connection string and my_schema with the name of the schema where you want to store your data.

Collecting and Exporting Data

Once you have configured the exporter, you can use the OpenTelemetry SDK to collect and export data. Here's an example in Node.js:

const { createTracer } = require('@opentelemetry/api-node');
const { SemanticConstraints } = require('@opentelemetry/semantic-constraints');

const tracer = createTracer('my-service', {
  instrumentations: [
    new SemanticConstraints({
      resource: {
        labels: {
          service: 'my-service',

const myService = {
  add: (a, b) => {
    const addSpan = tracer.startSpan('add', {
      kind: 'internal',

    const result = a + b;

      code: 0,
      message: 'Success',



    return result;

myService.add(1, 2);

This example creates a new tracer for a service called my-service and defines a method called add that logs some data. When you call myService.add(1, 2), OpenTelemetry will automatically collect and export the data to your PostgreSQL database.

Shutting Down

When you're done with your application, make sure to shut down the exporter and the tracer provider:

tracerProvider.shutdown.then(() => {

Related Links