Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Adds new configuration options to add custom tags (labels) to logs #2743

Merged
merged 5 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 2 additions & 20 deletions lib/agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
} = require('./util/attributes')
const synthetics = require('./synthetics')
const Harvester = require('./harvester')
const { createFeatureUsageMetrics } = require('./util/application-logging')

// Map of valid states to whether or not data collection is valid
const STATES = {
Expand Down Expand Up @@ -207,7 +208,7 @@
periodMs: config.event_harvest_config.report_period_ms,
limit: config.event_harvest_config.harvest_limits.analytic_event_data,
config,
enabled: (config) => config.transaction_events.enabled

Check warning on line 211 in lib/agent.js

View workflow job for this annotation

GitHub Actions / lint (lts/*)

'config' is already declared in the upper scope on line 159 column 16
},
this
)
Expand All @@ -218,7 +219,7 @@
limit: config.event_harvest_config.harvest_limits.custom_event_data,
metricNames: NAMES.CUSTOM_EVENTS,
config,
enabled: (config) => config.custom_insights_events.enabled

Check warning on line 222 in lib/agent.js

View workflow job for this annotation

GitHub Actions / lint (lts/*)

'config' is already declared in the upper scope on line 159 column 16
},
this
)
Expand All @@ -228,7 +229,7 @@
periodMs: DEFAULT_HARVEST_INTERVAL_MS,
limit: MAX_ERROR_TRACES_DEFAULT,
config,
enabled: (config) => config.error_collector.enabled && config.collect_errors

Check warning on line 232 in lib/agent.js

View workflow job for this annotation

GitHub Actions / lint (lts/*)

'config' is already declared in the upper scope on line 159 column 16
},
this.collector,
this.harvester
Expand All @@ -239,7 +240,7 @@
periodMs: config.event_harvest_config.report_period_ms,
limit: config.event_harvest_config.harvest_limits.error_event_data,
config,
enabled: (config) => config.error_collector.enabled && config.error_collector.capture_events

Check warning on line 243 in lib/agent.js

View workflow job for this annotation

GitHub Actions / lint (lts/*)

'config' is already declared in the upper scope on line 159 column 16
},
this
)
Expand Down Expand Up @@ -405,7 +406,7 @@
*/
Agent.prototype.onConnect = function onConnect(shouldImmediatelyHarvest, callback) {
this.harvester.update(this.config)
generateLoggingSupportMetrics(this)
createFeatureUsageMetrics(this)

if (this.config.certificates && this.config.certificates.length > 0) {
this.metrics.getOrCreateMetric(NAMES.FEATURES.CERTIFICATES).incrementCallCount()
Expand Down Expand Up @@ -953,23 +954,4 @@
}
}

/**
* Increments the call counts of application logging supportability metrics
* on every connect cycle
*
* @param {object} agent Instantiation of Node.js agent
*/
function generateLoggingSupportMetrics(agent) {
const loggingConfig = agent.config.application_logging
const logNames = NAMES.LOGGING

const configKeys = ['metrics', 'forwarding', 'local_decorating']
configKeys.forEach((configValue) => {
const configFlag =
loggingConfig.enabled && loggingConfig[`${configValue}`].enabled ? 'enabled' : 'disabled'
const metricName = logNames[`${configValue.toUpperCase()}`]
agent.metrics.getOrCreateMetric(`${metricName}${configFlag}`).incrementCallCount()
})
}

module.exports = Agent
8 changes: 7 additions & 1 deletion lib/aggregators/log-aggregator.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
'use strict'

const logger = require('../logger').child({ component: 'logs_aggregator' })
const { isLogLabelingEnabled } = require('../../lib/util/application-logging')
const EventAggregator = require('./event-aggregator')

const NAMES = require('../metrics/names')
Expand Down Expand Up @@ -56,7 +57,12 @@ class LogAggregator extends EventAggregator {
return
}

const commonAttrs = this.agent.getServiceLinkingMetadata()
let commonAttrs = this.agent.getServiceLinkingMetadata()

if (isLogLabelingEnabled(this.agent.config)) {
commonAttrs = { ...commonAttrs, ...this.agent.config.loggingLabels }
}

return [
{
common: { attributes: commonAttrs },
Expand Down
3 changes: 1 addition & 2 deletions lib/collector/facts.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
const fetchSystemInfo = require('../system-info')
const defaultLogger = require('../logger').child({ component: 'facts' })
const os = require('os')
const parseLabels = require('../util/label-parser')

module.exports = facts

Expand Down Expand Up @@ -49,7 +48,7 @@ async function facts(agent, callback, { logger = defaultLogger } = {}) {
environment: environment,
settings: agent.config.publicSettings(),
high_security: agent.config.high_security,
labels: parseLabels(agent.config.labels),
labels: agent.config.parsedLabels,
bizob2828 marked this conversation as resolved.
Show resolved Hide resolved
metadata: Object.keys(process.env).reduce((obj, key) => {
if (key.startsWith('NEW_RELIC_METADATA_')) {
obj[key] = process.env[key]
Expand Down
30 changes: 30 additions & 0 deletions lib/config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const harvestConfigValidator = require('./harvest-config-validator')
const mergeServerConfig = new MergeServerConfig()
const { boolean: isTruthular } = require('./formatters')
const configDefinition = definition()
const parseLabels = require('../util/label-parser')

/**
* CONSTANTS -- we gotta lotta 'em
Expand Down Expand Up @@ -195,9 +196,38 @@ function Config(config) {

// 9. Set instance attribute filter using updated context
this.attributeFilter = new AttributeFilter(this)

// 10. Setup labels for both `collector/facts` and application logging
this.parsedLabels = parseLabels(this.labels, logger)
this.loggingLabels = this._setApplicationLoggingLabels()
}
util.inherits(Config, EventEmitter)

/**
* Compares the labels list to the application logging excluded label list and removes any labels that need to be excluded.
* Then prefixing each label with "tags."
*
* assigns labels to `config.loggingLabels`
*/
Config.prototype._setApplicationLoggingLabels = function setApplicationLoggingLabels() {
if (this.application_logging.forwarding.labels.enabled === false) {
return
}

this.application_logging.forwarding.labels.exclude =
this.application_logging.forwarding.labels.exclude.map((k) => k.toLowerCase())

return this.parsedLabels.reduce((filteredLabels, label) => {
if (
!this.application_logging.forwarding.labels.exclude.includes(label.label_type.toLowerCase())
) {
filteredLabels[`tags.${label.label_type}`] = label.label_value
}

return filteredLabels
}, {})
}

/**
* Because this module and logger depend on each other, the logger needs
* a way to inject the actual logger instance once it's constructed.
Expand Down
3 changes: 2 additions & 1 deletion lib/metrics/names.js
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,8 @@ const LOGGING = {
SENT: `${LOGGING_FORWARDING_PREFIX}/Sent`,
FORWARDING: `${LOGGING_FORWARDING_PREFIX}/${NODEJS.PREFIX}`,
METRICS: `${SUPPORTABILITY.LOGGING}/Metrics/${NODEJS.PREFIX}`,
LOCAL_DECORATING: `${SUPPORTABILITY.LOGGING}/LocalDecorating/${NODEJS.PREFIX}`
LOCAL_DECORATING: `${SUPPORTABILITY.LOGGING}/LocalDecorating/${NODEJS.PREFIX}`,
LABELS: `${SUPPORTABILITY.LOGGING}/Labels/${NODEJS.PREFIX}`
}

const KAFKA = {
Expand Down
58 changes: 58 additions & 0 deletions lib/util/application-logging.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,16 @@ utils.isLogForwardingEnabled = function isLogForwardingEnabled(config, agent) {
)
}

/**
* Checks if application_logging.forwarding.labels is enabled
*
* @param {object} config agent config
* @returns {boolean} is labeling enabled
*/
utils.isLogLabelingEnabled = function isLogLabelingEnabled(config) {
return !!config.application_logging.forwarding.labels.enabled
}

/**
* Increments both `Logging/lines` and `Logging/lines/<level>` call count
*
Expand Down Expand Up @@ -108,3 +118,51 @@ function getLogLevel(level) {
}
return logLevel
}

/**
* Increments the enabled/disabled metrics for the top line application logging features:
* 1. Supportability/Logging/Metrics/Nodejs/<enabled|disabled>
* 2. Supportability/Logging/Forwarding/Nodejs/<enabled|disabled>
* 3. Supportability/Logging/LocalDecorating/Nodejs/<enabled|disabled>
* 4. Supportability/Logging/Labels/Nodejs/<enabled|disabled>
*
* Run in `agent.onConnect`
*
* @param {Agent} agent instance
*/
utils.createFeatureUsageMetrics = function createFeatureUsageMetrics(agent) {
const { config, metrics } = agent
const loggingConfig = config.application_logging.enabled
metrics
.getOrCreateMetric(
`${LOGGING.METRICS}${
loggingConfig && config.application_logging.metrics.enabled ? 'enabled' : 'disabled'
}`
)
.incrementCallCount()
metrics
.getOrCreateMetric(
`${LOGGING.FORWARDING}${
loggingConfig && config.application_logging.forwarding.enabled ? 'enabled' : 'disabled'
}`
)
.incrementCallCount()
metrics
.getOrCreateMetric(
`${LOGGING.LOCAL_DECORATING}${
loggingConfig && config.application_logging.local_decorating.enabled
? 'enabled'
: 'disabled'
}`
)
.incrementCallCount()
metrics
.getOrCreateMetric(
`${LOGGING.LABELS}${
loggingConfig && config.application_logging.forwarding.labels.enabled
? 'enabled'
: 'disabled'
}`
)
.incrementCallCount()
}
13 changes: 7 additions & 6 deletions lib/util/label-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@

// this creates a copy of trim that can be used with map
const trim = Function.prototype.call.bind(String.prototype.trim)
const logger = require('../logger').child({ component: 'label-parser' })
const stringify = require('json-stringify-safe')

function parse(labels) {
// pass in parent logger to avoid circular deps
function parse(labels, parentLogger) {
const logger = parentLogger.child({ component: 'label-parser' })
let results

if (!labels) {
Expand All @@ -25,8 +26,8 @@
results = fromMap(labels)
}

results.warnings.forEach(function logWarnings(messaage) {
logger.warn(messaage)
results.warnings.forEach(function logWarnings(message) {
logger.warn(message)
})

return results.labels
Expand Down Expand Up @@ -106,11 +107,11 @@
try {
warnings.unshift('Partially Invalid Label Setting: ' + stringify(map))
} catch (err) {
logger.debug(err, 'Failed to stringify labels')
warnings.unshift('Failed to stringify labels: ' + err.message)

Check warning on line 110 in lib/util/label-parser.js

View check run for this annotation

Codecov / codecov/patch

lib/util/label-parser.js#L110

Added line #L110 was not covered by tests
}
}

return { labels: labels, warnings: warnings }
return { labels, warnings }
}

function truncate(str, max) {
Expand Down
17 changes: 10 additions & 7 deletions test/unit/agent/agent.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -949,7 +949,7 @@ test('when event_harvest_config update on connect with a valid config', async (t
})

test('logging supportability on connect', async (t) => {
const keys = ['Forwarding', 'Metrics', 'LocalDecorating']
const keys = ['Forwarding', 'Metrics', 'LocalDecorating', 'Labels']

t.beforeEach((ctx) => {
ctx.nr = {}
Expand All @@ -967,12 +967,13 @@ test('logging supportability on connect', async (t) => {
agent.config.application_logging.metrics.enabled = false
agent.config.application_logging.forwarding.enabled = false
agent.config.application_logging.local_decorating.enabled = false
agent.config.application_logging.forwarding.labels.enabled = false
agent.onConnect(false, () => {
for (const key of keys) {
const disabled = agent.metrics.getMetric(`Supportability/Logging/${key}/Nodejs/disabled`)
const enabled = agent.metrics.getMetric(`Supportability/Logging/${key}/Nodejs/enabled`)
assert.equal(disabled.callCount, 1)
assert.equal(enabled, undefined)
assert.equal(disabled.callCount, 1, `${key} should be disabled`)
assert.equal(enabled, undefined, `${key} should not be enabled`)
}
end()
})
Expand All @@ -987,12 +988,13 @@ test('logging supportability on connect', async (t) => {
agent.config.application_logging.metrics.enabled = true
agent.config.application_logging.forwarding.enabled = true
agent.config.application_logging.local_decorating.enabled = true
agent.config.application_logging.forwarding.labels.enabled = true
agent.onConnect(false, () => {
for (const key of keys) {
const disabled = agent.metrics.getMetric(`Supportability/Logging/${key}/Nodejs/disabled`)
const enabled = agent.metrics.getMetric(`Supportability/Logging/${key}/Nodejs/enabled`)
assert.equal(disabled.callCount, 1)
assert.equal(enabled, undefined)
assert.equal(disabled.callCount, 1, `${key} should be disabled`)
assert.equal(enabled, undefined, `${key} should not be enabled`)
}
end()
})
Expand All @@ -1006,12 +1008,13 @@ test('logging supportability on connect', async (t) => {
agent.config.application_logging.metrics.enabled = true
agent.config.application_logging.forwarding.enabled = true
agent.config.application_logging.local_decorating.enabled = true
agent.config.application_logging.forwarding.labels.enabled = true
agent.onConnect(false, () => {
for (const key of keys) {
const disabled = agent.metrics.getMetric(`Supportability/Logging/${key}/Nodejs/disabled`)
const enabled = agent.metrics.getMetric(`Supportability/Logging/${key}/Nodejs/enabled`)
assert.equal(enabled.callCount, 1)
assert.equal(disabled, undefined)
assert.equal(enabled.callCount, 1, `${key} should be enabled`)
assert.equal(disabled, undefined, `${key} should not be enabled`)
}
end()
})
Expand Down
48 changes: 47 additions & 1 deletion test/unit/aggregators/log-aggregator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ const assert = require('node:assert')
const LogAggregator = require('../../../lib/aggregators/log-aggregator')
const Metrics = require('../../../lib/metrics')
const helper = require('../../lib/agent_helper')

const RUN_ID = 1337
const LIMIT = 5

Expand Down Expand Up @@ -41,6 +40,21 @@ test('Log Aggregator', async (t) => {
harvest_limits: {
log_event_data: 42
}
},
application_logging: {
metrics: {
enabled: true
},
local_decorating: {
enabled: true
},
forwarding: {
enabled: true,
labels: {
enabled: true,
exclude: []
}
}
}
}
}
Expand Down Expand Up @@ -175,6 +189,38 @@ test('Log Aggregator', async (t) => {
logEventAggregator.addBatch(logs, priority)
assert.equal(logEventAggregator.getEvents().length, 3)
})

await t.test('add labels to logs when enabled', (t) => {
const { agent, commonAttrs, logEventAggregator, log } = t.nr
const expectedLabels = {
'tags.label1': 'value1',
'tags.LABEL2-ALSO': 'value3'
}
agent.config.loggingLabels = expectedLabels

logEventAggregator.add(log)
const payload = logEventAggregator._toPayloadSync()
assert.deepStrictEqual(payload, [
{ common: { attributes: { ...commonAttrs, ...expectedLabels } }, logs: [log] }
])
})

await t.test(
'should not add labels to logs when `application_logging.forwarding.enabled` is false',
(t) => {
const { agent, commonAttrs, logEventAggregator, log } = t.nr
const expectedLabels = {
'tags.label1': 'value1',
'tags.LABEL2-ALSO': 'value3'
}
agent.config.loggingLabels = expectedLabels
agent.config.application_logging.forwarding.labels.enabled = false

logEventAggregator.add(log)
const payload = logEventAggregator._toPayloadSync()
assert.deepStrictEqual(payload, [{ common: { attributes: { ...commonAttrs } }, logs: [log] }])
}
)
})

test('big red button', async (t) => {
Expand Down
Loading
Loading