github.com/newrelic/go-agent@v3.26.0+incompatible/_integrations/nrpq/example/main.go (about)

     1  // Copyright 2020 New Relic Corporation. All rights reserved.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  package main
     5  
     6  import (
     7  	"context"
     8  	"database/sql"
     9  	"fmt"
    10  	"os"
    11  	"time"
    12  
    13  	newrelic "github.com/newrelic/go-agent"
    14  	_ "github.com/newrelic/go-agent/_integrations/nrpq"
    15  )
    16  
    17  func mustGetEnv(key string) string {
    18  	if val := os.Getenv(key); "" != val {
    19  		return val
    20  	}
    21  	panic(fmt.Sprintf("environment variable %s unset", key))
    22  }
    23  
    24  func main() {
    25  	// docker run --rm -e POSTGRES_PASSWORD=docker -p 5432:5432 postgres
    26  	db, err := sql.Open("nrpostgres", "host=localhost port=5432 user=postgres dbname=postgres password=docker sslmode=disable")
    27  	if err != nil {
    28  		panic(err)
    29  	}
    30  
    31  	cfg := newrelic.NewConfig("PostgreSQL App", mustGetEnv("NEW_RELIC_LICENSE_KEY"))
    32  	cfg.Logger = newrelic.NewDebugLogger(os.Stdout)
    33  	app, err := newrelic.NewApplication(cfg)
    34  	if nil != err {
    35  		panic(err)
    36  	}
    37  	app.WaitForConnection(5 * time.Second)
    38  	txn := app.StartTransaction("postgresQuery", nil, nil)
    39  
    40  	ctx := newrelic.NewContext(context.Background(), txn)
    41  	row := db.QueryRowContext(ctx, "SELECT count(*) FROM pg_catalog.pg_tables")
    42  	var count int
    43  	row.Scan(&count)
    44  
    45  	txn.End()
    46  	app.Shutdown(5 * time.Second)
    47  
    48  	fmt.Println("number of entries in pg_catalog.pg_tables", count)
    49  }