Saltar a contenido

New Relic Cheatsheet

Instalación

Infrastructure Agent

Platform Command
Ubuntu/Debian INLINE_CODE_10
RHEL/CentOS INLINE_CODE_11
macOS INLINE_CODE_12
Windows (PowerShell) INLINE_CODE_13
Docker INLINE_CODE_14

New Relic CLI

__TABLE_94_

APM Agents

Language Command
Node.js INLINE_CODE_19
Python INLINE_CODE_20
Java INLINE_CODE_21
Ruby INLINE_CODE_22 (add to Gemfile)
PHP INLINE_CODE_23 (Ubuntu) or INLINE_CODE_24 (RHEL)
.NET Download from INLINE_CODE_25

Comandos básicos

CLI Gestión del perfil

Command Description
INLINE_CODE_26 Add new profile with API key
INLINE_CODE_27 List all configured profiles
INLINE_CODE_28 Set default profile
INLINE_CODE_29 Delete a profile
INLINE_CODE_30 View profile details

Entity Management

Command Description
INLINE_CODE_31 Search for entities by name
INLINE_CODE_32 Search entities by type
INLINE_CODE_33 Get detailed entity information
INLINE_CODE_34 List all tags for an entity
INLINE_CODE_35 Add tag to entity
INLINE_CODE_36 Remove tag from entity

Infrastructure Agent Control

Command Description
INLINE_CODE_37 Check agent status
INLINE_CODE_38 Start infrastructure agent
INLINE_CODE_39 Stop infrastructure agent
INLINE_CODE_40 Restart infrastructure agent
INLINE_CODE_41 Enable agent at boot
INLINE_CODE_42 View agent logs in real-time
INLINE_CODE_43 Test configuration without starting
INLINE_CODE_44 Display agent version

Advanced Usage

NRQL Queries

Command Description
INLINE_CODE_45 Execute basic NRQL query
INLINE_CODE_46 Query with faceting
INLINE_CODE_47 Search logs with filtering
INLINE_CODE_48 Get percentiles with JSON output
INLINE_CODE_49 Calculate rate with time series

Deployment Management

Command Description
INLINE_CODE_50 Create deployment marker
INLINE_CODE_51 Create detailed deployment marker
INLINE_CODE_52 List all deployments for application

Workload Management

Command Description
INLINE_CODE_53 Create new workload
INLINE_CODE_54 Get workload details
INLINE_CODE_55 Update workload name
INLINE_CODE_56 Delete workload
INLINE_CODE_57 List all workloads in account

Alert Management

Command Description
INLINE_CODE_58 Create alert policy
INLINE_CODE_59 List all alert policies
INLINE_CODE_60 List conditions for policy
INLINE_CODE_61 List notification channels

Dashboard Management

__TABLE_103_

Configuración

Configuración del agente de infraestructura (INLINE_CODE_66)

# Required: License key
license_key: YOUR_LICENSE_KEY

# Optional: Custom display name
display_name: web-server-01

# Logging configuration
log_file: /var/log/newrelic-infra/newrelic-infra.log
log_level: info  # Options: error, warn, info, debug, trace

# Proxy configuration
proxy: http://proxy.example.com:8080
proxy_validate_certificates: true

# Custom attributes (tags)
custom_attributes:
  environment: production
  team: platform
  region: us-east-1

# Metrics configuration
disable_all_plugins: false
metrics_network_sample_rate: 10  # seconds
metrics_process_sample_rate: 20  # seconds
metrics_storage_sample_rate: 20  # seconds

# Process monitoring
enable_process_metrics: true

APM Agent Configuration (Node.js - newrelic.js_)

'use strict'

exports.config = {
  app_name: ['My Application'],
  license_key: 'YOUR_LICENSE_KEY',

  logging: {
    level: 'info',
    filepath: 'stdout'
  },

  // Distributed tracing
  distributed_tracing: {
    enabled: true
  },

  // Transaction tracer
  transaction_tracer: {
    enabled: true,
    transaction_threshold: 'apdex_f',
    record_sql: 'obfuscated',
    explain_threshold: 500
  },

  // Error collector
  error_collector: {
    enabled: true,
    ignore_status_codes: [404]
  },

  // Custom attributes
  attributes: {
    include: ['request.parameters.*'],
    exclude: ['request.headers.cookie']
  }
}

Python Agent Configuration (newrelic.ini)

[newrelic]
license_key = YOUR_LICENSE_KEY
app_name = Python Application

# Logging
log_file = stdout
log_level = info

# Distributed tracing
distributed_tracing.enabled = true

# Transaction tracer
transaction_tracer.enabled = true
transaction_tracer.transaction_threshold = apdex_f
transaction_tracer.record_sql = obfuscated
transaction_tracer.explain_threshold = 0.5

# Error collector
error_collector.enabled = true
error_collector.ignore_status_codes = 404

# Browser monitoring
browser_monitoring.auto_instrument = true

# Custom attributes
attributes.include = request.parameters.*
attributes.exclude = request.headers.cookie

CLI Configuration (~/.newrelic/newrelic-cli.json)

{
  "defaultProfile": "production",
  "profiles": {
    "production": {
      "apiKey": "YOUR_USER_API_KEY",
      "region": "us",
      "accountId": "YOUR_ACCOUNT_ID"
    },
    "staging": {
      "apiKey": "YOUR_STAGING_API_KEY",
      "region": "us",
      "accountId": "YOUR_STAGING_ACCOUNT_ID"
    }
  }
}

Common Use Cases

Use Case 1: Monitor Application Performance

# Install Node.js APM agent
npm install newrelic --save

# Generate configuration
cp node_modules/newrelic/newrelic.js .

# Edit configuration file with your license key
# license_key: 'YOUR_LICENSE_KEY'
# app_name: ['My Application']

# Add to the first line of your main application file
# require('newrelic');

# Start application
node app.js

# Query transaction performance
newrelic nrql query --accountId YOUR_ACCOUNT_ID \
  --query "SELECT average(duration), percentile(duration, 95) FROM Transaction WHERE appName = 'My Application' SINCE 1 hour ago"

Caso de uso 2: Establecer monitorización de infraestructura con etiquetas personalizadas

# Install infrastructure agent
curl -Ls https://download.newrelic.com/install/newrelic-cli/scripts/install.sh | bash

# Configure with custom attributes
sudo tee /etc/newrelic-infra.yml << EOF
license_key: YOUR_LICENSE_KEY
display_name: web-server-01
custom_attributes:
  environment: production
  team: platform
  datacenter: us-east-1
  role: webserver
EOF

# Start the agent
sudo systemctl start newrelic-infra
sudo systemctl enable newrelic-infra

# Verify it's reporting
newrelic entity search --name "web-server-01"

# Query infrastructure metrics
newrelic nrql query --accountId YOUR_ACCOUNT_ID \
  --query "SELECT average(cpuPercent), average(memoryUsedPercent) FROM SystemSample WHERE environment = 'production' FACET hostname SINCE 1 hour ago"

Use Case 3: Create Deployment Markers for Release Tracking

# Configure CLI profile
newrelic profile add --profile production \
  --apiKey YOUR_USER_API_KEY \
  --region us \
  --accountId YOUR_ACCOUNT_ID

# Get application ID
APP_ID=$(newrelic entity search --name "My Application" --type APPLICATION | grep -oP 'id: \K\d+')

# Create deployment marker during CI/CD
newrelic apm deployment create \
  --applicationId $APP_ID \
  --revision "v2.5.0" \
  --changelog "Added new feature X, fixed bug Y" \
  --description "Production deployment from Jenkins" \
  --user "$USER"

# Query performance before and after deployment
newrelic nrql query --accountId YOUR_ACCOUNT_ID \
  --query "SELECT average(duration) FROM Transaction WHERE appName = 'My Application' SINCE 2 hours ago TIMESERIES 10 minutes"

Use Case 4: Centralized Log Management

# Configure infrastructure agent to forward logs
sudo tee -a /etc/newrelic-infra.yml << EOF
log_forward:
  - name: application-logs
    file: /var/log/myapp/*.log
    attributes:
      logtype: application
      environment: production
EOF

# Restart agent
sudo systemctl restart newrelic-infra

# Search logs for errors
newrelic nrql query --accountId YOUR_ACCOUNT_ID \
  --query "SELECT * FROM Log WHERE logtype = 'application' AND message LIKE '%ERROR%' SINCE 30 minutes ago LIMIT 100"

# Analyze error patterns
newrelic nrql query --accountId YOUR_ACCOUNT_ID \
  --query "SELECT count(*) FROM Log WHERE logtype = 'application' AND message LIKE '%ERROR%' FACET message SINCE 1 day ago"

Use Case 5: Create Custom Dashboard with CLI

# Create dashboard with multiple widgets
newrelic dashboard create --accountId YOUR_ACCOUNT_ID << 'EOF'
{
  "name": "Production Overview",
  "permissions": "PUBLIC_READ_WRITE",
  "pages": [
    {
      "name": "Application Performance",
      "widgets": [
        {
          "title": "Average Response Time",
          "visualization": { "id": "viz.line" },
          "rawConfiguration": {
            "nrqlQueries": [
              {
                "accountId": YOUR_ACCOUNT_ID,
                "query": "SELECT average(duration) FROM Transaction TIMESERIES AUTO"
              }
            ]
          }
        }
      ]
    }
  ]
}
EOF

# List dashboards
newrelic dashboard list --accountId YOUR_ACCOUNT_ID

Buenas prácticas

  • Utilice Atributos Personalizados: Etiquete todas las entidades con metadatos ambientales, de equipo y de propósito para un mejor filtrado y organización. Añadir atributos personalizados en los archivos de configuración de agente para clasificar automáticamente todas las métricas.

  • Implement Distributed Tracing: Enable distributed tracing in all APM agents to track requests across microservices. Esto proporciona visibilidad de extremo a extremo y ayuda a identificar los cuellos de botella en arquitecturas complejas.

  • Configurar Marcadores de Despliegue: Crear marcadores de implementación para cada lanzamiento de producción para correlacionar cambios de rendimiento con implementaciones de código. Esto reduce drásticamente el tiempo de solución de problemas cuando surgen problemas.

  • Configure Alert Policies Properly: Use alertas de referencia para umbrales dinámicos y alertas estáticas para límites conocidos. Configura múltiples canales de notificación y usa inteligencia de incidentes para reducir la fatiga de alerta.

  • Optimizar la retención de datos: Utilice herramientas de gestión de datos para controlar la ingestión y retención de datos. Suelte métricas innecesarias, datos agregados apropiadamente y utilice muestreo para aplicaciones de alto volumen para gestionar costos.

Cargas de trabajo de aprendizaje: entidades relacionadas con el grupo en cargas de trabajo para supervisar juntas las pilas de aplicaciones completas. Esto proporciona una visión unificada del estado de salud y simplifica la colaboración del equipo.

  • Use NRQL Efectivamente: Master NRQL para consultas personalizadas y paneles. Usar FACET para agrupar, TIMESERIES_ para tendencias, y percentile() para métricas de rendimiento significativas en lugar de promedios.

Implement Synthetic Monitoring: Establecer monitores sintéticos para viajes críticos de usuario y puntos finales de API desde múltiples ubicaciones geográficas. Esto proporciona alerta proactiva antes de que los usuarios experimenten problemas.

  • Cumpla tus claves de API: Utilice las teclas de API de usuario para operaciones CLI y claves de licencia para los agentes. Rotar las teclas regularmente, utilizar diferentes teclas por medio ambiente, y nunca comprometer claves para el control de versiones.

Troubleshooting

__TABLE_104_

Quick Reference: Common NRQL Queries

-- Average response time by application
SELECT average(duration) FROM Transaction FACET appName SINCE 1 hour ago

-- Error rate percentage
SELECT percentage(count(*), WHERE error IS true) FROM Transaction SINCE 1 hour ago

-- 95th and 99th percentile response times
SELECT percentile(duration, 95, 99) FROM Transaction SINCE 1 day ago TIMESERIES

-- Top 10 slowest transactions
SELECT average(duration), count(*) FROM Transaction FACET name SINCE 1 hour ago LIMIT 10

-- Infrastructure CPU usage
SELECT average(cpuPercent) FROM SystemSample FACET hostname SINCE 1 hour ago

-- Log error count by message
SELECT count(*) FROM Log WHERE level = 'error' FACET message SINCE 1 hour ago

-- Request throughput per minute
SELECT rate(count(*), 1 minute) FROM Transaction TIMESERIES SINCE 1 hour ago

-- Database query performance
SELECT average(databaseDuration) FROM Transaction FACET databaseType SINCE 1 hour ago