@@ -25,12 +25,8 @@ const {
25
25
} = require ( '@elastic/ecs-helpers' )
26
26
27
27
const { hasOwnProperty } = Object . prototype
28
+ let triedElasticApmImport = false
28
29
let elasticApm = null
29
- try {
30
- elasticApm = require ( 'elastic-apm-node' )
31
- } catch ( ex ) {
32
- // Silently ignore.
33
- }
34
30
35
31
// Create options for `pino(...)` that configure it for ecs-logging output.
36
32
//
@@ -68,13 +64,27 @@ function createEcsPinoOptions (opts) {
68
64
69
65
let apm = null
70
66
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
+ }
78
88
}
79
89
80
90
let isServiceNameInBindings = false
0 commit comments