forked from elastic/apm-agent-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrace-pg.js
More file actions
executable file
·78 lines (68 loc) · 2.41 KB
/
trace-pg.js
File metadata and controls
executable file
·78 lines (68 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env node --unhandled-rejections=strict
/*
* Copyright Elasticsearch B.V. and other contributors where applicable.
* Licensed under the BSD 2-Clause License; you may not use this file except in
* compliance with the BSD 2-Clause License.
*/
// A small example showing Elastic APM tracing of a script using `pg`.
//
// By default this will use a Postgres on localhost with user 'postgres'.
// You can use:
// npm run docker:start postgres
// to start a Postgres container. Then `npm run docker:stop` to stop it.
const apm = require('../').start({ // elastic-apm-node
serviceName: 'example-trace-pg'
})
const { Client, Query } = require('pg')
const client = new Client({
user: process.env.PGUSER || 'postgres'
})
client.connect(function (err) {
console.warn('Connected (err=%s)', err)
})
// 1. Callback style
// For tracing spans to be created, there must be an active transaction.
// Typically, a transaction is automatically started for incoming HTTP
// requests to a Node.js server. However, because this script is not running
// an HTTP server, we manually start a transaction. More details at:
// https://www.elastic.co/guide/en/apm/agent/nodejs/current/custom-transactions.html
apm.startTransaction('t1')
client.query('SELECT $1::text as message', ['hi'], (err, res) => {
console.log('[t1] err=%s res=%s', err && err.message, !err && res.rows[0].message)
})
client.query('SELECT $1::text as message', ['bye'], (err, res) => {
console.log('[t1] err=%s res=%s', err && err.message, !err && res.rows[0].message)
apm.endTransaction()
})
// 2. Using streaming style, i.e. using a `Submittable` as node-postgres calls it.
const t2 = apm.startTransaction('t2')
const q = client.query(new Query('select 1 + 1 as solution'))
q.on('error', (err) => {
console.log('[t2] Failure: err is', err)
t2.end()
})
q.on('row', (row) => {
console.log('[t2] solution is %s', row.solution)
})
q.on('end', () => {
console.log('[t2] Success')
t2.end()
})
// 3. Promise style
apm.startTransaction('t3')
client.query('select 1 + 1 as solution')
.then(function (result) {
console.log('[t3] Success: solution is %s', result.rows[0].solution)
})
.catch(function (err) {
console.log('[t3] Failure: err is', err)
})
.finally(function () {
apm.endTransaction()
})
// TODO: 4. async/await style
// Lazily shutdown client after everything above is finished.
setTimeout(() => {
console.log('Done')
client.end()
}, 1000)