New Relic
Full-stack observability platform. Integrates APM, infrastructure monitoring, browser monitoring, and mobile monitoring. Real-time performance analysis and AI-assisted problem resolution.
Server
New Relic
Overview
New Relic is a full-stack observability platform that integrates APM, infrastructure monitoring, browser monitoring, and mobile monitoring. It provides real-time performance analysis and AI-assisted problem resolution capabilities. As a veteran provider in the APM field, it supports digital transformation with AI-assisted automation and full-stack observability, continuing growth through its cloud-first strategy.
Details
New Relic is a veteran provider in the APM field with extensive experience in application performance monitoring. It supports digital transformation initiatives with AI-assisted automation and comprehensive full-stack observability capabilities. The platform continues growth through its cloud-first strategy, offering unified monitoring across applications, infrastructure, and user experiences. With advanced analytics, machine learning capabilities, and extensive integrations, New Relic provides enterprise-grade observability solutions for modern cloud-native environments.
Key Technical Features
- Full-stack Observability: Unified monitoring across applications, infrastructure, and user experience
- AI-assisted Analysis: Machine learning-powered anomaly detection and root cause analysis
- Real-time Performance Monitoring: Low-latency data collection and analysis
- Distributed Tracing: End-to-end transaction tracking across microservices
- Custom Dashboards: Flexible visualization and alerting capabilities
- Extensive Integrations: 600+ technology integrations
Use Cases
- Application performance monitoring (APM)
- Infrastructure monitoring and optimization
- Digital experience monitoring
- Error tracking and debugging
- Capacity planning and scaling
- Business metrics and KPI tracking
Pros and Cons
Pros
- Comprehensive Platform: Full-stack observability in single solution
- AI-powered Insights: Advanced machine learning for anomaly detection
- Enterprise Scale: Proven scalability for large organizations
- Rich Integrations: Extensive ecosystem of technology integrations
- User Experience Focus: Strong capabilities for digital experience monitoring
- Professional Support: Enterprise-grade support and services
Cons
- High Cost: Premium pricing for enterprise features
- Complexity: Learning curve for advanced features and configuration
- Data Retention Limits: Costs increase with longer data retention requirements
- Vendor Lock-in: Proprietary platform with limited portability
- Performance Impact: Agent overhead in high-traffic applications
- Limited Customization: SaaS model limits deep customization options
Reference Pages
Code Examples
Installation and Basic Setup
# Node.js Agent Installation
npm install newrelic
# Create newrelic.js configuration file
cp node_modules/newrelic/newrelic.js ./newrelic.js
# Java Agent Installation
curl -O https://download.newrelic.com/newrelic/java-agent/newrelic-agent/current/newrelic-java.zip
unzip newrelic-java.zip
# Python Agent Installation
pip install newrelic
# Ruby Agent Installation
gem install newrelic_rpm
# .NET Agent Installation (Windows)
# Download from https://download.newrelic.com/dot_net_agent/latest_release/
# Docker Integration
docker run -d \
--name newrelic-infra \
--network=host \
--cap-add=SYS_PTRACE \
--privileged \
--pid=host \
-v "/:/host:ro" \
-v "/var/run/docker.sock:/var/run/docker.sock" \
-e NRIA_LICENSE_KEY=YOUR_LICENSE_KEY \
newrelic/infrastructure:latest
# Kubernetes DaemonSet
kubectl apply -f https://download.newrelic.com/infrastructure_agent/integrations/kubernetes/newrelic-infrastructure-k8s-latest.yaml
Application Configuration
// newrelic.js (Node.js)
'use strict'
exports.config = {
app_name: ['Web Application Production'],
license_key: 'YOUR_LICENSE_KEY_HERE',
// Logging configuration
logging: {
level: 'info',
filepath: 'stdout',
enabled: true
},
// Transaction tracer configuration
transaction_tracer: {
enabled: true,
transaction_threshold: 'apdex_f',
record_sql: 'obfuscated',
explain_threshold: 500,
slow_sql: {
enabled: true,
max_samples: 10
}
},
// Error collector configuration
error_collector: {
enabled: true,
ignore_status_codes: [404, 401],
ignore_classes: ['HttpResponseError'],
capture_events: true,
max_event_samples_stored: 100
},
// Browser monitoring
browser_monitoring: {
enable: true,
debug: false
},
// Application logging
application_logging: {
enabled: true,
forwarding: {
enabled: true,
max_samples_stored: 10000
},
metrics: {
enabled: true
},
local_decorating: {
enabled: true
}
},
// Distributed tracing
distributed_tracing: {
enabled: true
},
// Span events
span_events: {
enabled: true,
max_samples_stored: 2000
},
// Custom attributes
attributes: {
enabled: true,
include: ['request.headers.userAgent', 'request.headers.referer'],
exclude: ['request.headers.authorization', 'request.headers.cookie']
},
// Security settings
security: {
agent: {
enabled: true
},
detection: {
rci: {
enabled: true
},
rxss: {
enabled: true
}
}
},
// Custom events
custom_insights_events: {
enabled: true,
max_samples_stored: 10000
}
}
// Application integration (Express.js)
require('newrelic');
const express = require('express');
const newrelic = require('newrelic');
const app = express();
// Custom middleware for tracking
app.use((req, res, next) => {
// Add custom attributes
newrelic.addCustomAttributes({
'user.id': req.user?.id,
'request.path': req.path,
'request.method': req.method,
'user.plan': req.user?.plan || 'free'
});
next();
});
// Custom metric recording
app.get('/api/orders', async (req, res) => {
const startTime = Date.now();
try {
// Record custom metric
newrelic.recordMetric('Custom/API/Orders/RequestCount', 1);
const orders = await getOrders(req.query);
// Record business metric
newrelic.recordMetric('Custom/Business/OrdersRetrieved', orders.length);
// Record timing
const duration = Date.now() - startTime;
newrelic.recordMetric('Custom/API/Orders/ResponseTime', duration);
res.json(orders);
} catch (error) {
// Record error
newrelic.noticeError(error, {
'custom.endpoint': '/api/orders',
'custom.query': JSON.stringify(req.query)
});
res.status(500).json({ error: 'Internal Server Error' });
}
});
// Custom event recording
app.post('/api/purchase', async (req, res) => {
try {
const purchase = await processPurchase(req.body);
// Record custom event
newrelic.recordCustomEvent('Purchase', {
userId: req.user.id,
amount: purchase.amount,
currency: purchase.currency,
productId: purchase.productId,
category: purchase.category,
paymentMethod: purchase.paymentMethod
});
res.json({ success: true, orderId: purchase.id });
} catch (error) {
newrelic.noticeError(error);
res.status(500).json({ error: 'Purchase failed' });
}
});
Infrastructure Monitoring
# newrelic-infra.yml
license_key: YOUR_LICENSE_KEY_HERE
display_name: Production Web Server
# Logging configuration
log:
level: info
file: /var/log/newrelic-infra/newrelic-infra.log
rotate:
max_size_mb: 100
max_files: 5
# Network monitoring
network:
ignore_interfaces:
- lo
- docker0
# Process monitoring
enable_process_metrics: true
process_sample_rate: 60
# Custom attributes
custom_attributes:
environment: production
datacenter: us-east-1
team: platform
service_tier: web
# Integration configurations
integrations:
# MySQL integration
- name: nri-mysql
env:
HOSTNAME: localhost
PORT: 3306
USERNAME: newrelic
PASSWORD: YOUR_MYSQL_PASSWORD
DATABASE: information_schema
interval: 30s
labels:
env: production
role: database
# Redis integration
- name: nri-redis
env:
HOSTNAME: localhost
PORT: 6379
PASSWORD: YOUR_REDIS_PASSWORD
interval: 30s
labels:
env: production
role: cache
# Nginx integration
- name: nri-nginx
env:
STATUS_URL: http://localhost/nginx_status
interval: 30s
labels:
env: production
role: webserver
# Docker integration
- name: nri-docker
env:
DOCKER_API_VERSION: 1.24
interval: 30s
# Log forwarding
logs:
- name: nginx-access
file: /var/log/nginx/access.log
attributes:
logtype: nginx-access
service: web
- name: nginx-error
file: /var/log/nginx/error.log
attributes:
logtype: nginx-error
service: web
- name: application
file: /var/log/app/application.log
attributes:
logtype: application
service: api
# Proxy configuration (if needed)
proxy: http://proxy.example.com:8080
# Agent update
auto_update: true
update_channel: stable
Synthetic Monitoring
// Synthetic API monitoring script
const assert = require('assert');
// API endpoint test
$webDriver.get('https://api.example.com/health')
.then(() => {
return $webDriver.findElement($driver.By.css('body')).getText();
})
.then((body) => {
const response = JSON.parse(body);
assert.equal(response.status, 'healthy');
assert(response.timestamp);
console.log('API health check passed');
});
// Complex user flow test
$webDriver.get('https://app.example.com/login')
.then(() => {
// Wait for page load
return $webDriver.wait($driver.until.elementLocated($driver.By.id('username')), 10000);
})
.then(() => {
// Login flow
return $webDriver.findElement($driver.By.id('username')).sendKeys('[email protected]');
})
.then(() => {
return $webDriver.findElement($driver.By.id('password')).sendKeys('password123');
})
.then(() => {
return $webDriver.findElement($driver.By.css('button[type="submit"]')).click();
})
.then(() => {
// Wait for redirect
return $webDriver.wait($driver.until.urlContains('/dashboard'), 10000);
})
.then(() => {
// Verify dashboard elements
return $webDriver.wait($driver.until.elementLocated($driver.By.css('.dashboard-widget')), 5000);
})
.then(() => {
console.log('User flow test completed successfully');
});
// Performance timing measurement
$webDriver.executeScript('return window.performance.timing')
.then((timing) => {
const loadTime = timing.loadEventEnd - timing.navigationStart;
const domReady = timing.domContentLoadedEventEnd - timing.navigationStart;
console.log(`Page load time: ${loadTime}ms`);
console.log(`DOM ready time: ${domReady}ms`);
// Assert performance thresholds
assert(loadTime < 3000, 'Page load time should be less than 3 seconds');
assert(domReady < 2000, 'DOM ready time should be less than 2 seconds');
});
Custom Dashboards and Alerting
-- NRQL Queries for Custom Dashboards
-- Application Performance Overview
SELECT average(duration)
FROM Transaction
WHERE appName = 'Web Application Production'
FACET name
TIMESERIES
-- Error Rate Analysis
SELECT count(*) as 'Total Requests',
filter(count(*), WHERE error IS true) as 'Errors',
percentage(count(*), WHERE error IS true) as 'Error Rate'
FROM Transaction
WHERE appName = 'Web Application Production'
SINCE 1 hour ago
-- Infrastructure Health
SELECT latest(cpuPercent) as 'CPU %',
latest(memoryUsedPercent) as 'Memory %',
latest(diskUsedPercent) as 'Disk %'
FROM SystemSample
WHERE hostname = 'web-server-01'
TIMESERIES
-- Business Metrics
SELECT sum(amount) as 'Total Revenue',
count(*) as 'Transaction Count',
average(amount) as 'Average Transaction'
FROM CustomEvent
WHERE eventType = 'Purchase'
SINCE 1 day ago
FACET currency
-- User Experience Monitoring
SELECT percentile(duration, 50, 95, 99)
FROM PageView
WHERE appName = 'Web Application'
TIMESERIES
-- Database Performance
SELECT average(duration) as 'Avg Query Time',
count(*) as 'Query Count'
FROM DatabaseSample
WHERE database = 'production_db'
FACET sql
LIMIT 10
-- Custom Alert Conditions
-- High Error Rate Alert
SELECT percentage(count(*), WHERE error IS true)
FROM Transaction
WHERE appName = 'Web Application Production'
-- High Response Time Alert
SELECT average(duration)
FROM Transaction
WHERE appName = 'Web Application Production'
AND name = '/api/orders'
-- Infrastructure Alert
SELECT average(cpuPercent)
FROM SystemSample
WHERE hostname LIKE 'web-server-%'
-- Business Metrics Alert
SELECT count(*)
FROM CustomEvent
WHERE eventType = 'Purchase'
AND amount > 1000
Advanced Configuration
// Advanced New Relic configuration with custom instrumentation
const newrelic = require('newrelic');
// Custom instrumentation for database queries
newrelic.instrument('mysql', function(shim, mysql, moduleName) {
shim.recordQuery(mysql.Connection.prototype, 'query', function(shim, fn, fnName, args) {
return {
stream: shim.FIRST,
query: shim.FIRST,
callback: shim.LAST,
name: 'MySQL',
record: true
};
});
});
// Custom business logic instrumentation
newrelic.instrument('my-custom-module', function(shim, module, moduleName) {
shim.recordGeneric(module.prototype, 'processOrder', 'Custom/ProcessOrder');
shim.recordGeneric(module.prototype, 'calculateShipping', 'Custom/CalculateShipping');
});
// Custom middleware for enhanced tracking
const customNewRelicMiddleware = (req, res, next) => {
// Start custom timing
const timer = newrelic.startTime();
// Add custom attributes based on request
newrelic.addCustomAttributes({
'request.userAgent': req.get('user-agent'),
'request.ip': req.ip,
'request.size': req.get('content-length') || 0,
'user.authenticated': !!req.user,
'user.role': req.user?.role || 'anonymous'
});
// Track API version usage
if (req.path.startsWith('/api/v')) {
const version = req.path.split('/')[2];
newrelic.recordMetric(`Custom/API/Version/${version}`, 1);
}
// Enhanced response tracking
const originalSend = res.send;
res.send = function(data) {
// Record response size
const responseSize = Buffer.byteLength(data || '', 'utf8');
newrelic.addCustomAttributes({
'response.size': responseSize
});
// Record custom metrics
newrelic.recordMetric('Custom/Response/Size', responseSize);
// End custom timing
const duration = newrelic.endTime(timer);
newrelic.recordMetric('Custom/Request/TotalTime', duration);
return originalSend.call(this, data);
};
next();
};
// Error boundary with enhanced reporting
const enhancedErrorHandler = (error, req, res, next) => {
// Enhanced error reporting
newrelic.noticeError(error, {
'error.context': 'express_handler',
'request.url': req.url,
'request.method': req.method,
'request.body': JSON.stringify(req.body),
'user.id': req.user?.id,
'session.id': req.sessionID
});
// Record error metrics
newrelic.recordMetric('Custom/Errors/Total', 1);
newrelic.recordMetric(`Custom/Errors/${error.name || 'Unknown'}`, 1);
res.status(500).json({
error: 'Internal Server Error',
requestId: newrelic.getTraceMetadata().traceId
});
};
// Background job monitoring
class JobProcessor {
static async processJob(jobData) {
const transaction = newrelic.startBackgroundTransaction('Job/Process', () => {
return this.doProcessJob(jobData);
});
return transaction;
}
static async doProcessJob(jobData) {
const timer = newrelic.startTime();
try {
// Add job context
newrelic.addCustomAttributes({
'job.type': jobData.type,
'job.priority': jobData.priority,
'job.queueTime': Date.now() - jobData.queuedAt
});
// Process job
const result = await this.executeJob(jobData);
// Record success metrics
newrelic.recordMetric('Custom/Jobs/Success', 1);
newrelic.recordMetric(`Custom/Jobs/${jobData.type}/Success`, 1);
return result;
} catch (error) {
// Record error
newrelic.noticeError(error, {
'job.type': jobData.type,
'job.data': JSON.stringify(jobData)
});
newrelic.recordMetric('Custom/Jobs/Error', 1);
newrelic.recordMetric(`Custom/Jobs/${jobData.type}/Error`, 1);
throw error;
} finally {
// Record timing
const duration = newrelic.endTime(timer);
newrelic.recordMetric('Custom/Jobs/Duration', duration);
newrelic.recordMetric(`Custom/Jobs/${jobData.type}/Duration`, duration);
}
}
}
Troubleshooting
# Check New Relic agent status
curl http://localhost:8080/status
# View agent logs (Node.js)
tail -f newrelic_agent.log
# Test connection
newrelic-admin validate-config
# Python agent debug
NEW_RELIC_LOG_LEVEL=debug python app.py
# Java agent diagnostics
java -javaagent:newrelic.jar -Dnewrelic.config.log_level=finest YourApp
# Infrastructure agent status
sudo systemctl status newrelic-infra
tail -f /var/log/newrelic-infra/newrelic-infra.log
# Check data collection
curl -H "Api-Key: YOUR_API_KEY" \
"https://api.newrelic.com/v2/applications.json"
# Validate NRQL queries
curl -H "X-Query-Key: YOUR_QUERY_KEY" \
-G "https://insights-api.newrelic.com/v1/accounts/YOUR_ACCOUNT_ID/query" \
--data-urlencode "nrql=SELECT * FROM Transaction LIMIT 1"
# Agent configuration test
newrelic-admin validate-config newrelic.ini
# Network connectivity test
telnet collector.newrelic.com 443
# Memory usage analysis
ps aux | grep newrelic
cat /proc/$(pgrep newrelic)/status
# Check for data transmission
tcpdump -i any host collector.newrelic.com
# License key validation
newrelic-admin test-license-key YOUR_LICENSE_KEY
# Generate agent report
newrelic-admin generate-config