or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

aws-lambda.mdbrowser-monitoring.mdcustom-attributes.mdcustom-instrumentation.mddistributed-tracing.mderror-handling.mdindex.mdllm-monitoring.mdmetrics-events.mdsegments-timing.mdtransaction-management.mdurl-naming-rules.mdutilities.md

custom-attributes.mddocs/

0

# Custom Attributes & Data

1

2

Add custom metadata to transactions, spans, and events for enhanced filtering and analysis in New Relic dashboards.

3

4

## Capabilities

5

6

### Add Custom Attribute

7

8

Add a custom attribute to both the current transaction and span.

9

10

```javascript { .api }

11

/**

12

* Add a custom attribute to the current transaction and span.

13

* Disabled in high security mode.

14

* @param {string} key - The attribute name

15

* @param {string|number|boolean} value - The attribute value (must be serializable)

16

* @returns {false|undefined} Returns false on error, undefined on success

17

*/

18

function addCustomAttribute(key, value);

19

```

20

21

**Usage Examples:**

22

23

```javascript

24

const newrelic = require('newrelic');

25

26

// Add user context

27

newrelic.addCustomAttribute('userId', user.id);

28

newrelic.addCustomAttribute('userPlan', 'premium');

29

newrelic.addCustomAttribute('isNewUser', false);

30

31

// Add business context

32

newrelic.addCustomAttribute('orderValue', 149.99);

33

newrelic.addCustomAttribute('paymentMethod', 'credit_card');

34

newrelic.addCustomAttribute('promoCode', 'SAVE20');

35

```

36

37

### Add Multiple Custom Attributes

38

39

Add multiple custom attributes at once to transaction and span.

40

41

```javascript { .api }

42

/**

43

* Add multiple custom attributes to the current transaction and span

44

* @param {object} attributes - Object containing key-value pairs of attributes

45

*/

46

function addCustomAttributes(attributes);

47

```

48

49

**Usage Example:**

50

51

```javascript

52

newrelic.addCustomAttributes({

53

userId: '12345',

54

planType: 'enterprise',

55

region: 'us-east-1',

56

featureFlag: 'new-checkout',

57

experimentGroup: 'variant-b'

58

});

59

```

60

61

### Add Custom Span Attribute

62

63

Add a custom attribute to the current span only (not the transaction).

64

65

```javascript { .api }

66

/**

67

* Add a custom attribute to the current span only.

68

* Disabled in high security mode.

69

* @param {string} key - The attribute name

70

* @param {string|number|boolean} value - The attribute value (must be serializable)

71

* @returns {false|undefined} Returns false on error, undefined on success

72

*/

73

function addCustomSpanAttribute(key, value);

74

```

75

76

**Usage Example:**

77

78

```javascript

79

// Add span-specific context (useful for detailed tracing)

80

newrelic.addCustomSpanAttribute('cacheHit', true);

81

newrelic.addCustomSpanAttribute('queryComplexity', 'high');

82

newrelic.addCustomSpanAttribute('retryCount', 2);

83

```

84

85

### Add Multiple Custom Span Attributes

86

87

Add multiple custom attributes to the current span only.

88

89

```javascript { .api }

90

/**

91

* Add multiple custom attributes to the current span only

92

* @param {object} attributes - Object containing key-value pairs of attributes

93

*/

94

function addCustomSpanAttributes(attributes);

95

```

96

97

**Usage Example:**

98

99

```javascript

100

newrelic.addCustomSpanAttributes({

101

dbConnectionPool: 'primary',

102

queryType: 'SELECT',

103

indexUsed: true,

104

rowsReturned: 42

105

});

106

```

107

108

### Set User ID

109

110

Assign a user identifier that appears on transactions, traces, and errors.

111

112

```javascript { .api }

113

/**

114

* Set the enduser.id attribute on transactions, traces, and errors

115

* @param {string} id - Unique user identifier

116

*/

117

function setUserID(id);

118

```

119

120

**Usage Example:**

121

122

```javascript

123

// Set user ID at login

124

app.post('/login', (req, res) => {

125

const user = authenticateUser(req.body);

126

if (user) {

127

newrelic.setUserID(user.id);

128

// This user ID will now appear on all subsequent transactions

129

}

130

});

131

132

// Clear user ID at logout

133

app.post('/logout', (req, res) => {

134

newrelic.setUserID(''); // Clear the user ID

135

});

136

```

137

138

## Attribute Restrictions

139

140

### Reserved Names

141

142

The following attribute names are reserved and cannot be used:

143

- `nr_flatten_leading`

144

145

### Data Type Requirements

146

147

Custom attributes must be:

148

- **String**: Any string value

149

- **Number**: Integer or float

150

- **Boolean**: true or false

151

152

Objects, arrays, functions, and other complex types are not allowed.

153

154

### High Security Mode

155

156

When high security mode is enabled:

157

- `addCustomAttribute()` returns `false` and logs a warning

158

- `addCustomSpanAttribute()` returns `false` and logs a warning

159

- Custom attributes are completely disabled

160

161

### Configuration Control

162

163

Custom attributes can be disabled via configuration:

164

- `api.custom_attributes_enabled: false` disables all custom attribute methods

165

- Methods return `false` when disabled

166

167

## Common Usage Patterns

168

169

### User Context Tracking

170

171

```javascript

172

// Middleware to add user context to all transactions

173

app.use((req, res, next) => {

174

if (req.user) {

175

newrelic.addCustomAttributes({

176

userId: req.user.id,

177

userRole: req.user.role,

178

accountType: req.user.accountType,

179

subscriptionTier: req.user.subscription?.tier

180

});

181

182

newrelic.setUserID(req.user.id);

183

}

184

next();

185

});

186

```

187

188

### Business Metrics Tracking

189

190

```javascript

191

app.post('/api/orders', (req, res) => {

192

newrelic.addCustomAttributes({

193

orderValue: req.body.total,

194

paymentMethod: req.body.payment.method,

195

shippingMethod: req.body.shipping.method,

196

itemCount: req.body.items.length,

197

hasPromoCode: !!req.body.promoCode

198

});

199

200

// Process order...

201

});

202

```

203

204

### Feature Flag and A/B Testing

205

206

```javascript

207

function addExperimentContext(userId, experiments) {

208

const attributes = {};

209

210

experiments.forEach(experiment => {

211

attributes[`experiment_${experiment.name}`] = experiment.variant;

212

});

213

214

newrelic.addCustomAttributes(attributes);

215

}

216

217

// Usage

218

addExperimentContext(user.id, [

219

{ name: 'checkout_flow', variant: 'new_design' },

220

{ name: 'recommendation_algo', variant: 'ml_based' }

221

]);

222

```

223

224

### Database Operation Context

225

226

```javascript

227

async function performDatabaseQuery(query, params) {

228

newrelic.addCustomSpanAttributes({

229

queryType: query.type,

230

tableCount: query.tables.length,

231

hasJoins: query.joins.length > 0,

232

paramCount: params.length

233

});

234

235

const result = await database.execute(query, params);

236

237

newrelic.addCustomSpanAttribute('rowsAffected', result.rowCount);

238

239

return result;

240

}

241

```

242

243

### Error Context Enhancement

244

245

```javascript

246

try {

247

await processPayment(paymentData);

248

} catch (error) {

249

// Add context before reporting error

250

newrelic.addCustomAttributes({

251

paymentProvider: paymentData.provider,

252

paymentAmount: paymentData.amount,

253

customerTier: customer.tier

254

});

255

256

newrelic.noticeError(error);

257

throw error;

258

}

259

```

260

261

### Performance Tracking

262

263

```javascript

264

function trackPerformanceMetrics(operation, metrics) {

265

newrelic.addCustomSpanAttributes({

266

[`${operation}_duration`]: metrics.duration,

267

[`${operation}_memoryUsed`]: metrics.memoryDelta,

268

[`${operation}_cpuTime`]: metrics.cpuTime,

269

[`${operation}_cacheSize`]: metrics.cacheSize

270

});

271

}

272

273

// Usage

274

const startTime = Date.now();

275

const startMemory = process.memoryUsage().heapUsed;

276

277

await performOperation();

278

279

trackPerformanceMetrics('dataProcessing', {

280

duration: Date.now() - startTime,

281

memoryDelta: process.memoryUsage().heapUsed - startMemory,

282

cpuTime: process.cpuUsage().user,

283

cacheSize: cache.size

284

});

285

```