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

metrics-events.mddocs/

0

# Metrics & Events

1

2

Record custom metrics and events for business analytics and performance tracking beyond standard APM data.

3

4

## Capabilities

5

6

### Record Custom Metric

7

8

Record a custom metric with name and value for performance tracking.

9

10

```javascript { .api }

11

/**

12

* Record a custom metric, usually associated with a particular duration.

13

* The name gets prefixed with 'Custom/' when sent to New Relic.

14

* @param {string} name - The metric name following standard naming rules

15

* @param {number|object} value - Numeric value or metrics object

16

*/

17

function recordMetric(name, value);

18

```

19

20

**Usage Examples:**

21

22

```javascript

23

const newrelic = require('newrelic');

24

25

// Simple numeric metrics

26

newrelic.recordMetric('API/ResponseTime', 245.5);

27

newrelic.recordMetric('Cache/HitRate', 0.85);

28

newrelic.recordMetric('Queue/Size', 127);

29

30

// Advanced metrics object with full statistics

31

newrelic.recordMetric('Custom/BatchProcessor/Duration', {

32

count: 50, // Number of measurements

33

total: 12500, // Total time across all measurements (ms)

34

min: 100, // Minimum value (ms)

35

max: 500, // Maximum value (ms)

36

sumOfSquares: 425000, // Sum of squares for standard deviation

37

totalExclusive: 11800 // Optional: exclusive time

38

});

39

```

40

41

### Increment Counter Metric

42

43

Create or update a counter metric by incrementing its count.

44

45

```javascript { .api }

46

/**

47

* Create or update a custom metric that acts as a simple counter.

48

* @param {string} name - The metric name

49

* @param {number} [value] - Amount to increment by (defaults to 1, must be integer)

50

*/

51

function incrementMetric(name, value);

52

```

53

54

**Usage Examples:**

55

56

```javascript

57

// Simple counters

58

newrelic.incrementMetric('API/Requests'); // Increment by 1

59

newrelic.incrementMetric('Errors/ValidationFailed', 1);

60

newrelic.incrementMetric('Queue/Messages', 5); // Increment by 5

61

62

// Tracking business events

63

newrelic.incrementMetric('Business/Orders');

64

newrelic.incrementMetric('Business/SignUps');

65

newrelic.incrementMetric('Business/Cancellations');

66

```

67

68

### Record Custom Event

69

70

Record custom events for New Relic Insights analytics and querying.

71

72

```javascript { .api }

73

/**

74

* Record custom event data which can be queried in New Relic Insights.

75

* Disabled in high security mode.

76

* @param {string} eventType - Event type name (alphanumeric, <255 chars, matches /^[a-zA-Z0-9:_ ]+$/)

77

* @param {object} attributes - Event attributes (keys <255 chars, values must be string/number/boolean)

78

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

79

*/

80

function recordCustomEvent(eventType, attributes);

81

```

82

83

**Usage Examples:**

84

85

```javascript

86

// User behavior events

87

newrelic.recordCustomEvent('UserAction', {

88

action: 'purchase',

89

userId: '12345',

90

amount: 99.99,

91

category: 'electronics',

92

paymentMethod: 'credit_card',

93

timestamp: Date.now()

94

});

95

96

// Business process events

97

newrelic.recordCustomEvent('OrderProcessed', {

98

orderId: 'ORD-789123',

99

customerId: 'CUST-456',

100

orderValue: 249.50,

101

shippingMethod: 'express',

102

processingTime: 1250,

103

warehouseLocation: 'US-EAST-1'

104

});

105

106

// System performance events

107

newrelic.recordCustomEvent('CacheRefresh', {

108

cacheType: 'user_sessions',

109

itemCount: 15000,

110

refreshDuration: 3400,

111

memoryUsage: 128.5,

112

hitRateImprovement: 0.15

113

});

114

```

115

116

### Record Log Event

117

118

Send application log messages to New Relic for centralized logging.

119

120

```javascript { .api }

121

/**

122

* Send an application log message to New Relic.

123

* Only works if application log forwarding is enabled.

124

* @param {object} logEvent - Log event object

125

* @param {string} logEvent.message - Log message (required)

126

* @param {string} [logEvent.level] - Log level (defaults to 'UNKNOWN')

127

* @param {number} [logEvent.timestamp] - Timestamp (defaults to Date.now())

128

* @param {Error} [logEvent.error] - Associated error object

129

*/

130

function recordLogEvent(logEvent);

131

```

132

133

**Usage Examples:**

134

135

```javascript

136

// Basic log event

137

newrelic.recordLogEvent({

138

message: 'User login successful',

139

level: 'INFO'

140

});

141

142

// Log with custom timestamp

143

newrelic.recordLogEvent({

144

message: 'Payment processing started',

145

level: 'INFO',

146

timestamp: Date.now(),

147

userId: '12345',

148

orderId: 'ORD-789'

149

});

150

151

// Log with error

152

newrelic.recordLogEvent({

153

message: 'Database connection failed',

154

level: 'ERROR',

155

error: new Error('Connection timeout'),

156

retryAttempt: 3,

157

databaseHost: 'db-primary.example.com'

158

});

159

160

// Structured log event

161

newrelic.recordLogEvent({

162

message: 'API request processed',

163

level: 'INFO',

164

endpoint: '/api/users',

165

method: 'POST',

166

statusCode: 201,

167

responseTime: 145,

168

userId: 'user-456'

169

});

170

```

171

172

## Event Type Validation

173

174

### Custom Event Types

175

176

Event types must:

177

- Match the pattern `/^[a-zA-Z0-9:_ ]+$/`

178

- Be less than 256 characters long

179

- Contain only alphanumeric characters, colons, underscores, and spaces

180

181

### Attribute Restrictions

182

183

Event attributes must have:

184

- Keys shorter than 255 characters

185

- Values that are strings, numbers, or booleans (objects/arrays not allowed)

186

187

## Configuration and Security

188

189

### High Security Mode

190

191

When high security mode is enabled:

192

- `recordCustomEvent()` returns `false` and logs warning

193

- Custom events are completely disabled

194

195

### Configuration Controls

196

197

- `api.custom_events_enabled: false` - Disables custom events

198

- `custom_insights_events.enabled: false` - Disables custom events

199

- `application_logging.forwarding.enabled: false` - Disables log forwarding

200

201

## Common Usage Patterns

202

203

### Business Analytics

204

205

```javascript

206

// E-commerce tracking

207

function trackPurchase(order) {

208

newrelic.recordCustomEvent('Purchase', {

209

orderId: order.id,

210

customerId: order.customerId,

211

totalAmount: order.total,

212

itemCount: order.items.length,

213

paymentMethod: order.payment.method,

214

shippingCost: order.shipping.cost,

215

discountAmount: order.discount || 0,

216

isFirstPurchase: order.customer.isNew

217

});

218

219

newrelic.incrementMetric('Business/Orders');

220

newrelic.recordMetric('Business/Revenue', order.total);

221

}

222

```

223

224

### Performance Monitoring

225

226

```javascript

227

// Custom performance tracking

228

function trackOperationPerformance(operationName, duration, metadata = {}) {

229

newrelic.recordMetric(`Operations/${operationName}/Duration`, duration);

230

231

newrelic.recordCustomEvent('OperationCompleted', {

232

operation: operationName,

233

duration: duration,

234

...metadata

235

});

236

237

if (duration > 5000) {

238

newrelic.incrementMetric(`Operations/${operationName}/SlowOperations`);

239

}

240

}

241

242

// Usage

243

const startTime = Date.now();

244

await performDatabaseMigration();

245

const duration = Date.now() - startTime;

246

247

trackOperationPerformance('DatabaseMigration', duration, {

248

recordsProcessed: 150000,

249

tablesUpdated: 12,

250

memoryPeak: process.memoryUsage().heapUsed

251

});

252

```

253

254

### Feature Usage Tracking

255

256

```javascript

257

// Feature adoption metrics

258

function trackFeatureUsage(featureName, userId, metadata = {}) {

259

newrelic.incrementMetric(`Features/${featureName}/Usage`);

260

261

newrelic.recordCustomEvent('FeatureUsed', {

262

feature: featureName,

263

userId: userId,

264

timestamp: Date.now(),

265

...metadata

266

});

267

}

268

269

// Usage examples

270

trackFeatureUsage('AdvancedSearch', user.id, {

271

searchTerms: 3,

272

filtersUsed: ['category', 'price_range'],

273

resultsFound: 47

274

});

275

276

trackFeatureUsage('ExportData', user.id, {

277

format: 'csv',

278

recordCount: 2500,

279

fileSize: '1.2MB'

280

});

281

```

282

283

### Error and Warning Tracking

284

285

```javascript

286

// Custom error tracking with metrics

287

function trackApplicationError(errorType, error, context = {}) {

288

newrelic.incrementMetric(`Errors/${errorType}`);

289

290

newrelic.recordCustomEvent('ApplicationError', {

291

errorType: errorType,

292

errorMessage: error.message,

293

stack: error.stack,

294

userId: context.userId,

295

operation: context.operation,

296

timestamp: Date.now()

297

});

298

299

newrelic.recordLogEvent({

300

message: `${errorType}: ${error.message}`,

301

level: 'ERROR',

302

error: error,

303

...context

304

});

305

}

306

307

// Usage

308

try {

309

await processPayment(paymentData);

310

} catch (error) {

311

trackApplicationError('PaymentProcessingError', error, {

312

userId: user.id,

313

operation: 'processPayment',

314

paymentMethod: paymentData.method,

315

amount: paymentData.amount

316

});

317

throw error;

318

}

319

```

320

321

### System Health Monitoring

322

323

```javascript

324

// System metrics collection

325

function recordSystemMetrics() {

326

const memoryUsage = process.memoryUsage();

327

const cpuUsage = process.cpuUsage();

328

329

// Memory metrics

330

newrelic.recordMetric('System/Memory/HeapUsed', memoryUsage.heapUsed);

331

newrelic.recordMetric('System/Memory/HeapTotal', memoryUsage.heapTotal);

332

newrelic.recordMetric('System/Memory/RSS', memoryUsage.rss);

333

334

// CPU metrics

335

newrelic.recordMetric('System/CPU/User', cpuUsage.user);

336

newrelic.recordMetric('System/CPU/System', cpuUsage.system);

337

338

// System health event

339

newrelic.recordCustomEvent('SystemHealth', {

340

memoryHeapUsed: memoryUsage.heapUsed,

341

memoryHeapTotal: memoryUsage.heapTotal,

342

memoryRSS: memoryUsage.rss,

343

cpuUser: cpuUsage.user,

344

cpuSystem: cpuUsage.system,

345

uptime: process.uptime(),

346

loadAverage: os.loadavg()[0]

347

});

348

}

349

350

// Run every 60 seconds

351

setInterval(recordSystemMetrics, 60000);

352

```