github.com/newrelic/go-agent@v3.26.0+incompatible/_integrations/nrmysql/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  	"github.com/newrelic/go-agent"
    14  	_ "github.com/newrelic/go-agent/_integrations/nrmysql"
    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  	// Set up a local mysql docker container with:
    26  	// docker run -it -p 3306:3306 --net "bridge" -e MYSQL_ALLOW_EMPTY_PASSWORD=true mysql
    27  
    28  	db, err := sql.Open("nrmysql", "root@/information_schema")
    29  	if nil != err {
    30  		panic(err)
    31  	}
    32  
    33  	cfg := newrelic.NewConfig("MySQL App", mustGetEnv("NEW_RELIC_LICENSE_KEY"))
    34  	cfg.Logger = newrelic.NewDebugLogger(os.Stdout)
    35  	app, err := newrelic.NewApplication(cfg)
    36  	if nil != err {
    37  		panic(err)
    38  	}
    39  	app.WaitForConnection(5 * time.Second)
    40  	txn := app.StartTransaction("mysqlQuery", nil, nil)
    41  
    42  	ctx := newrelic.NewContext(context.Background(), txn)
    43  	row := db.QueryRowContext(ctx, "SELECT count(*) from tables")
    44  	var count int
    45  	row.Scan(&count)
    46  
    47  	txn.End()
    48  	app.Shutdown(5 * time.Second)
    49  
    50  	fmt.Println("number of tables in information_schema", count)
    51  }