|
| 1 | +/* |
| 2 | + * Copyright 2025 New Relic Corporation. All rights reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +'use strict' |
| 7 | + |
| 8 | +const logsApi = require('@opentelemetry/api-logs') |
| 9 | +const logsSdk = require('@opentelemetry/sdk-logs') |
| 10 | +const { |
| 11 | + isApplicationLoggingEnabled, |
| 12 | + isLogForwardingEnabled, |
| 13 | + isMetricsEnabled, |
| 14 | + incrementLoggingLinesMetrics |
| 15 | +} = require('#agentlib/util/application-logging.js') |
| 16 | + |
| 17 | +const defaultLogger = require('../../logger').child({ component: 'opentelemetry-metrics' }) |
| 18 | +const SetupSignal = require('../setup-signal.js') |
| 19 | +const NewRelicLoggerProvider = require('./proxying-provider.js') |
| 20 | +const NoOpExporter = require('./no-op-exporter.js') |
| 21 | +const normalizeTimestamp = require('./normalize-timestamp.js') |
| 22 | +const severityToString = require('./severity-to-string.js') |
| 23 | + |
| 24 | +class SetupLogs extends SetupSignal { |
| 25 | + constructor({ agent, logger = defaultLogger } = {}) { |
| 26 | + super({ agent, logger }) |
| 27 | + |
| 28 | + if (isApplicationLoggingEnabled(agent.config) === false) { |
| 29 | + logger.info('application logging disabled, skipping otel logs setup') |
| 30 | + return |
| 31 | + } |
| 32 | + |
| 33 | + agent.metrics |
| 34 | + .getOrCreateMetric('Supportability/Nodejs/OpenTelemetryBridge/Logs') |
| 35 | + .incrementCallCount() |
| 36 | + |
| 37 | + const exporter = new NoOpExporter() |
| 38 | + const processor = new logsSdk.BatchLogRecordProcessor(exporter) |
| 39 | + const otelProvider = new logsSdk.LoggerProvider({ |
| 40 | + processors: [processor] |
| 41 | + }) |
| 42 | + const provider = new NewRelicLoggerProvider({ |
| 43 | + agent, |
| 44 | + provider: otelProvider, |
| 45 | + emitHandler: nrEmitHandler |
| 46 | + }) |
| 47 | + logsApi.logs.setGlobalLoggerProvider(provider) |
| 48 | + |
| 49 | + function nrEmitHandler(record) { |
| 50 | + const level = severityToString(record.severityNumber ?? 0) |
| 51 | + if (isMetricsEnabled(agent.config) === true) { |
| 52 | + incrementLoggingLinesMetrics(level, agent.metrics) |
| 53 | + } |
| 54 | + |
| 55 | + // TODO: if we decide to support local decorating, implement it here |
| 56 | + |
| 57 | + if (isLogForwardingEnabled(agent.config, agent) === true) { |
| 58 | + const meta = agent.getLinkingMetadata(true) |
| 59 | + const timestamp = normalizeTimestamp(record.timestamp) |
| 60 | + const logData = { |
| 61 | + message: record.body, |
| 62 | + level, |
| 63 | + timestamp, |
| 64 | + ...record.attributes, |
| 65 | + ...meta |
| 66 | + } |
| 67 | + |
| 68 | + agent.logs.add(logData) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + agent.emit('otelLogsBootstrapped') |
| 73 | + } |
| 74 | + |
| 75 | + teardown() { |
| 76 | + logsApi.logs.disable() |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +module.exports = SetupLogs |
0 commit comments