Skip to content

Commit 17e5d6b

Browse files
authored
fix(pino): avoid circular-require between this and elastic-apm-node (elastic#80)
Now that elastic-apm-node uses this package for its own logging. Fixes: elastic#79
1 parent 318966e commit 17e5d6b

File tree

2 files changed

+29
-12
lines changed

2 files changed

+29
-12
lines changed

loggers/pino/CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
# @elastic/ecs-pino-format Changelog
22

3+
## Unreleased
4+
5+
- Fix a circular-require for code that uses both this package and
6+
'elastic-apm-node'.
7+
([#79](https://github.com/elastic/ecs-logging-nodejs/issues/79))
8+
9+
310
## v1.1.1
411

512
- The ecs-logging spec was [updated to allow "message" to be

loggers/pino/index.js

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,8 @@ const {
2525
} = require('@elastic/ecs-helpers')
2626

2727
const { hasOwnProperty } = Object.prototype
28+
let triedElasticApmImport = false
2829
let elasticApm = null
29-
try {
30-
elasticApm = require('elastic-apm-node')
31-
} catch (ex) {
32-
// Silently ignore.
33-
}
3430

3531
// Create options for `pino(...)` that configure it for ecs-logging output.
3632
//
@@ -68,13 +64,27 @@ function createEcsPinoOptions (opts) {
6864

6965
let apm = null
7066
let apmServiceName = null
71-
if (apmIntegration && elasticApm && elasticApm.isStarted && elasticApm.isStarted()) {
72-
apm = elasticApm
73-
// Elastic APM v3.11.0 added getServiceName(). Fallback to private `apm._conf`.
74-
// istanbul ignore next
75-
apmServiceName = apm.getServiceName
76-
? apm.getServiceName()
77-
: apm._conf.serviceName
67+
if (apmIntegration) {
68+
if (!triedElasticApmImport) {
69+
triedElasticApmImport = true
70+
// We lazily require this module here instead of at the top-level to
71+
// avoid a possible circular-require if the user code does
72+
// `require('@elastic/ecs-pino-format')` and has a "node_modules/"
73+
// where 'elastic-apm-node' shares the same ecs-pino-format install.
74+
try {
75+
elasticApm = require('elastic-apm-node')
76+
} catch (ex) {
77+
// Silently ignore.
78+
}
79+
}
80+
if (elasticApm && elasticApm.isStarted && elasticApm.isStarted()) {
81+
apm = elasticApm
82+
// Elastic APM v3.11.0 added getServiceName(). Fallback to private `apm._conf`.
83+
// istanbul ignore next
84+
apmServiceName = apm.getServiceName
85+
? apm.getServiceName()
86+
: apm._conf.serviceName
87+
}
7888
}
7989

8090
let isServiceNameInBindings = false

0 commit comments

Comments
 (0)