@@ -25,12 +25,8 @@ const {
2525} = require ( '@elastic/ecs-helpers' )
2626
2727const { hasOwnProperty } = Object . prototype
28+ let triedElasticApmImport = false
2829let 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