new-relic

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

New Relic

New Relic

Monitor applications and infrastructure with New Relic's observability platform.
使用New Relic可观测性平台监控应用与基础设施。

When to Use This Skill

何时使用该技能

Use this skill when:
  • Implementing full-stack observability
  • Setting up APM for applications
  • Monitoring infrastructure health
  • Creating custom dashboards and alerts
  • Implementing distributed tracing
在以下场景使用该技能:
  • 实施全栈可观测性
  • 为应用设置APM
  • 监控基础设施健康状态
  • 创建自定义仪表板与告警
  • 实现分布式追踪

Prerequisites

前提条件

  • New Relic account and license key
  • Application access for APM agents
  • Infrastructure access for host agents
  • New Relic账户与许可证密钥
  • 应用对APM代理的访问权限
  • 基础设施对主机代理的访问权限

Infrastructure Agent

基础设施代理

Linux Installation

Linux安装

bash
undefined
bash
undefined

Add repository and install

Add repository and install

Configure license key

Configure license key

sudo NEW_RELIC_API_KEY=<YOUR_API_KEY> NEW_RELIC_ACCOUNT_ID=<ACCOUNT_ID> /usr/local/bin/newrelic install
sudo NEW_RELIC_API_KEY=<YOUR_API_KEY> NEW_RELIC_ACCOUNT_ID=<ACCOUNT_ID> /usr/local/bin/newrelic install

Or manual configuration

Or manual configuration

echo "license_key: YOUR_LICENSE_KEY" | sudo tee -a /etc/newrelic-infra.yml sudo systemctl start newrelic-infra
undefined
echo "license_key: YOUR_LICENSE_KEY" | sudo tee -a /etc/newrelic-infra.yml sudo systemctl start newrelic-infra
undefined

Docker

Docker

yaml
undefined
yaml
undefined

docker-compose.yml

docker-compose.yml

version: '3.8'
services: newrelic-infra: image: newrelic/infrastructure:latest cap_add: - SYS_PTRACE privileged: true pid: "host" network_mode: "host" environment: - NRIA_LICENSE_KEY=${NEW_RELIC_LICENSE_KEY} - NRIA_DISPLAY_NAME=docker-host volumes: - /:/host:ro - /var/run/docker.sock:/var/run/docker.sock
undefined
version: '3.8'
services: newrelic-infra: image: newrelic/infrastructure:latest cap_add: - SYS_PTRACE privileged: true pid: "host" network_mode: "host" environment: - NRIA_LICENSE_KEY=${NEW_RELIC_LICENSE_KEY} - NRIA_DISPLAY_NAME=docker-host volumes: - /:/host:ro - /var/run/docker.sock:/var/run/docker.sock
undefined

Kubernetes

Kubernetes

bash
undefined
bash
undefined

Using Helm

Using Helm

helm repo add newrelic https://helm-charts.newrelic.com
helm install newrelic-bundle newrelic/nri-bundle
--namespace newrelic
--create-namespace
--set global.licenseKey=${NEW_RELIC_LICENSE_KEY}
--set global.cluster=my-cluster
--set newrelic-infrastructure.privileged=true
--set ksm.enabled=true
--set kubeEvents.enabled=true
--set logging.enabled=true
undefined
helm repo add newrelic https://helm-charts.newrelic.com
helm install newrelic-bundle newrelic/nri-bundle
--namespace newrelic
--create-namespace
--set global.licenseKey=${NEW_RELIC_LICENSE_KEY}
--set global.cluster=my-cluster
--set newrelic-infrastructure.privileged=true
--set ksm.enabled=true
--set kubeEvents.enabled=true
--set logging.enabled=true
undefined

APM Agents

APM代理

Node.js

Node.js

javascript
// At the very start of your application
require('newrelic');

// newrelic.js configuration
exports.config = {
  app_name: ['My Application'],
  license_key: process.env.NEW_RELIC_LICENSE_KEY,
  distributed_tracing: {
    enabled: true
  },
  logging: {
    level: 'info'
  },
  error_collector: {
    enabled: true,
    ignore_status_codes: [404]
  },
  transaction_tracer: {
    enabled: true,
    transaction_threshold: 'apdex_f',
    record_sql: 'obfuscated'
  }
};
bash
undefined
javascript
// At the very start of your application
require('newrelic');

// newrelic.js configuration
exports.config = {
  app_name: ['My Application'],
  license_key: process.env.NEW_RELIC_LICENSE_KEY,
  distributed_tracing: {
    enabled: true
  },
  logging: {
    level: 'info'
  },
  error_collector: {
    enabled: true,
    ignore_status_codes: [404]
  },
  transaction_tracer: {
    enabled: true,
    transaction_threshold: 'apdex_f',
    record_sql: 'obfuscated'
  }
};
bash
undefined

Install agent

Install agent

npm install newrelic
npm install newrelic

Run application

Run application

NEW_RELIC_LICENSE_KEY=xxx node -r newrelic app.js
undefined
NEW_RELIC_LICENSE_KEY=xxx node -r newrelic app.js
undefined

Python

Python

python
undefined
python
undefined

newrelic.ini

newrelic.ini

[newrelic] license_key = YOUR_LICENSE_KEY app_name = My Application distributed_tracing.enabled = true transaction_tracer.enabled = true error_collector.enabled = true browser_monitoring.auto_instrument = true

```bash
[newrelic] license_key = YOUR_LICENSE_KEY app_name = My Application distributed_tracing.enabled = true transaction_tracer.enabled = true error_collector.enabled = true browser_monitoring.auto_instrument = true

```bash

Install agent

Install agent

pip install newrelic
pip install newrelic

Generate config file

Generate config file

newrelic-admin generate-config YOUR_LICENSE_KEY newrelic.ini
newrelic-admin generate-config YOUR_LICENSE_KEY newrelic.ini

Run application

Run application

NEW_RELIC_CONFIG_FILE=newrelic.ini newrelic-admin run-program python app.py
NEW_RELIC_CONFIG_FILE=newrelic.ini newrelic-admin run-program python app.py

Or with gunicorn

Or with gunicorn

NEW_RELIC_CONFIG_FILE=newrelic.ini newrelic-admin run-program gunicorn app:app
undefined
NEW_RELIC_CONFIG_FILE=newrelic.ini newrelic-admin run-program gunicorn app:app
undefined

Java

Java

bash
undefined
bash
undefined

Download agent

Download agent

Configure newrelic.yml

Configure newrelic.yml

license_key: YOUR_LICENSE_KEY

license_key: YOUR_LICENSE_KEY

app_name: My Application

app_name: My Application

Run with agent

Run with agent

java -javaagent:/path/to/newrelic.jar -jar myapp.jar
undefined
java -javaagent:/path/to/newrelic.jar -jar myapp.jar
undefined

Go

Go

go
package main

import (
    "github.com/newrelic/go-agent/v3/newrelic"
    "net/http"
)

func main() {
    app, err := newrelic.NewApplication(
        newrelic.ConfigAppName("My Application"),
        newrelic.ConfigLicense("YOUR_LICENSE_KEY"),
        newrelic.ConfigDistributedTracerEnabled(true),
    )
    if err != nil {
        panic(err)
    }

    http.HandleFunc(newrelic.WrapHandleFunc(app, "/", indexHandler))
    http.ListenAndServe(":8080", nil)
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    txn := newrelic.FromContext(r.Context())
    txn.AddAttribute("user_id", "12345")
    w.Write([]byte("Hello, World!"))
}
go
package main

import (
    "github.com/newrelic/go-agent/v3/newrelic"
    "net/http"
)

func main() {
    app, err := newrelic.NewApplication(
        newrelic.ConfigAppName("My Application"),
        newrelic.ConfigLicense("YOUR_LICENSE_KEY"),
        newrelic.ConfigDistributedTracerEnabled(true),
    )
    if err != nil {
        panic(err)
    }

    http.HandleFunc(newrelic.WrapHandleFunc(app, "/", indexHandler))
    http.ListenAndServe(":8080", nil)
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    txn := newrelic.FromContext(r.Context())
    txn.AddAttribute("user_id", "12345")
    w.Write([]byte("Hello, World!"))
}

Custom Instrumentation

自定义埋点

Custom Events

自定义事件

python
import newrelic.agent
python
import newrelic.agent

Record custom event

Record custom event

newrelic.agent.record_custom_event('OrderPlaced', { 'order_id': '12345', 'amount': 99.99, 'customer_id': 'cust_001' })
undefined
newrelic.agent.record_custom_event('OrderPlaced', { 'order_id': '12345', 'amount': 99.99, 'customer_id': 'cust_001' })
undefined

Custom Metrics

自定义指标

python
import newrelic.agent
python
import newrelic.agent

Record custom metric

Record custom metric

newrelic.agent.record_custom_metric('Custom/OrderValue', 99.99)
newrelic.agent.record_custom_metric('Custom/OrderValue', 99.99)

With attributes

With attributes

newrelic.agent.record_custom_metric('Custom/ProcessingTime', processing_time, {'unit': 'milliseconds'} )
undefined
newrelic.agent.record_custom_metric('Custom/ProcessingTime', processing_time, {'unit': 'milliseconds'} )
undefined

Custom Spans

自定义Span

python
import newrelic.agent

@newrelic.agent.function_trace(name='process_payment')
def process_payment(order_id, amount):
    # This creates a custom span in the trace
    pass
python
import newrelic.agent

@newrelic.agent.function_trace(name='process_payment')
def process_payment(order_id, amount):
    # This creates a custom span in the trace
    pass

Manual span creation

Manual span creation

with newrelic.agent.FunctionTrace(name='custom_operation'): # Traced code pass
undefined
with newrelic.agent.FunctionTrace(name='custom_operation'): # Traced code pass
undefined

NRQL Queries

NRQL查询

Basic Queries

基础查询

sql
-- Transaction throughput
SELECT rate(count(*), 1 minute) FROM Transaction 
WHERE appName = 'My Application' 
SINCE 1 hour ago

-- Average response time
SELECT average(duration) FROM Transaction 
WHERE appName = 'My Application' 
SINCE 1 hour ago

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

-- Apdex score
SELECT apdex(duration, t: 0.5) FROM Transaction 
WHERE appName = 'My Application' 
SINCE 1 hour ago
sql
-- Transaction throughput
SELECT rate(count(*), 1 minute) FROM Transaction 
WHERE appName = 'My Application' 
SINCE 1 hour ago

-- Average response time
SELECT average(duration) FROM Transaction 
WHERE appName = 'My Application' 
SINCE 1 hour ago

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

-- Apdex score
SELECT apdex(duration, t: 0.5) FROM Transaction 
WHERE appName = 'My Application' 
SINCE 1 hour ago

Advanced Queries

高级查询

sql
-- Slowest transactions
SELECT average(duration) FROM Transaction 
WHERE appName = 'My Application' 
FACET name 
SINCE 1 hour ago 
ORDER BY average(duration) DESC 
LIMIT 10

-- Error breakdown
SELECT count(*) FROM TransactionError 
WHERE appName = 'My Application' 
FACET error.class 
SINCE 1 hour ago

-- Percentile response times
SELECT percentile(duration, 50, 90, 95, 99) FROM Transaction 
WHERE appName = 'My Application' 
SINCE 1 hour ago TIMESERIES

-- Custom event analysis
SELECT average(amount), count(*) FROM OrderPlaced 
FACET customer_id 
SINCE 1 day ago
sql
-- Slowest transactions
SELECT average(duration) FROM Transaction 
WHERE appName = 'My Application' 
FACET name 
SINCE 1 hour ago 
ORDER BY average(duration) DESC 
LIMIT 10

-- Error breakdown
SELECT count(*) FROM TransactionError 
WHERE appName = 'My Application' 
FACET error.class 
SINCE 1 hour ago

-- Percentile response times
SELECT percentile(duration, 50, 90, 95, 99) FROM Transaction 
WHERE appName = 'My Application' 
SINCE 1 hour ago TIMESERIES

-- Custom event analysis
SELECT average(amount), count(*) FROM OrderPlaced 
FACET customer_id 
SINCE 1 day ago

Dashboards

仪表板

Dashboard JSON

仪表板JSON

json
{
  "name": "Application Dashboard",
  "pages": [
    {
      "name": "Overview",
      "widgets": [
        {
          "title": "Throughput",
          "visualization": {"id": "viz.line"},
          "configuration": {
            "nrqlQueries": [
              {
                "accountId": 12345,
                "query": "SELECT rate(count(*), 1 minute) FROM Transaction WHERE appName = 'My Application' SINCE 1 hour ago TIMESERIES"
              }
            ]
          }
        },
        {
          "title": "Error Rate",
          "visualization": {"id": "viz.billboard"},
          "configuration": {
            "nrqlQueries": [
              {
                "accountId": 12345,
                "query": "SELECT percentage(count(*), WHERE error IS true) FROM Transaction WHERE appName = 'My Application' SINCE 1 hour ago"
              }
            ]
          }
        }
      ]
    }
  ]
}
json
{
  "name": "Application Dashboard",
  "pages": [
    {
      "name": "Overview",
      "widgets": [
        {
          "title": "Throughput",
          "visualization": {"id": "viz.line"},
          "configuration": {
            "nrqlQueries": [
              {
                "accountId": 12345,
                "query": "SELECT rate(count(*), 1 minute) FROM Transaction WHERE appName = 'My Application' SINCE 1 hour ago TIMESERIES"
              }
            ]
          }
        },
        {
          "title": "Error Rate",
          "visualization": {"id": "viz.billboard"},
          "configuration": {
            "nrqlQueries": [
              {
                "accountId": 12345,
                "query": "SELECT percentage(count(*), WHERE error IS true) FROM Transaction WHERE appName = 'My Application' SINCE 1 hour ago"
              }
            ]
          }
        }
      ]
    }
  ]
}

Alerts

告警

Alert Condition (NRQL)

告警条件(NRQL)

json
{
  "name": "High Error Rate",
  "type": "static",
  "nrql": {
    "query": "SELECT percentage(count(*), WHERE error IS true) FROM Transaction WHERE appName = 'My Application'"
  },
  "valueFunction": "single_value",
  "terms": [
    {
      "threshold": 5,
      "thresholdOccurrences": "all",
      "thresholdDuration": 300,
      "operator": "above",
      "priority": "critical"
    },
    {
      "threshold": 2,
      "thresholdOccurrences": "all",
      "thresholdDuration": 300,
      "operator": "above",
      "priority": "warning"
    }
  ]
}
json
{
  "name": "High Error Rate",
  "type": "static",
  "nrql": {
    "query": "SELECT percentage(count(*), WHERE error IS true) FROM Transaction WHERE appName = 'My Application'"
  },
  "valueFunction": "single_value",
  "terms": [
    {
      "threshold": 5,
      "thresholdOccurrences": "all",
      "thresholdDuration": 300,
      "operator": "above",
      "priority": "critical"
    },
    {
      "threshold": 2,
      "thresholdOccurrences": "all",
      "thresholdDuration": 300,
      "operator": "above",
      "priority": "warning"
    }
  ]
}

Alert Policy

告警策略

json
{
  "name": "Application Alerts",
  "incident_preference": "PER_CONDITION_AND_TARGET",
  "conditions": [
    {
      "name": "High Response Time",
      "type": "apm_app_metric",
      "entities": ["My Application"],
      "metric": "response_time_web",
      "condition_scope": "application",
      "terms": [
        {
          "duration": "5",
          "operator": "above",
          "threshold": "1",
          "priority": "critical"
        }
      ]
    }
  ]
}
json
{
  "name": "Application Alerts",
  "incident_preference": "PER_CONDITION_AND_TARGET",
  "conditions": [
    {
      "name": "High Response Time",
      "type": "apm_app_metric",
      "entities": ["My Application"],
      "metric": "response_time_web",
      "condition_scope": "application",
      "terms": [
        {
          "duration": "5",
          "operator": "above",
          "threshold": "1",
          "priority": "critical"
        }
      ]
    }
  ]
}

Logs in Context

关联日志

Python Configuration

Python配置

python
undefined
python
undefined

newrelic.ini

newrelic.ini

[newrelic] application_logging.enabled = true application_logging.forwarding.enabled = true application_logging.metrics.enabled = true application_logging.local_decorating.enabled = true
undefined
[newrelic] application_logging.enabled = true application_logging.forwarding.enabled = true application_logging.metrics.enabled = true application_logging.local_decorating.enabled = true
undefined

Log Forwarding

日志转发

yaml
undefined
yaml
undefined

newrelic-infra.yml

newrelic-infra.yml

log:
  • name: application-logs file: /var/log/myapp/*.log attributes: service: myapp environment: production
undefined
log:
  • name: application-logs file: /var/log/myapp/*.log attributes: service: myapp environment: production
undefined

Common Issues

常见问题

Issue: No Data Appearing

问题:无数据显示

Problem: Agent not reporting to New Relic Solution: Verify license key, check network connectivity, review agent logs
问题描述:代理未向New Relic上报数据 解决方案:验证许可证密钥、检查网络连通性、查看代理日志

Issue: Missing Transactions

问题:缺失事务数据

Problem: Some transactions not captured Solution: Check instrumentation coverage, verify framework support
问题描述:部分事务未被捕获 解决方案:检查埋点覆盖范围、验证框架支持情况

Issue: High Overhead

问题:性能开销过高

Problem: APM agent impacting performance Solution: Adjust sampling rate, disable unnecessary features
问题描述:APM代理影响应用性能 解决方案:调整采样率、禁用不必要的功能

Best Practices

最佳实践

  • Use meaningful application names
  • Implement distributed tracing across services
  • Set up service maps for dependency visualization
  • Configure appropriate alert thresholds
  • Use custom attributes for business context
  • Implement logs in context for correlation
  • Set up workloads for service grouping
  • Regular review of unused dashboards and alerts
  • 使用有意义的应用名称
  • 在服务间实现分布式追踪
  • 设置服务映射以可视化依赖关系
  • 配置合适的告警阈值
  • 使用自定义属性添加业务上下文
  • 实现关联日志以进行关联分析
  • 设置工作负载进行服务分组
  • 定期清理未使用的仪表板与告警

Related Skills

相关技能

  • datadog - Alternative monitoring platform
  • prometheus-grafana - Open source monitoring
  • alerting-oncall - Alert management
  • datadog - 替代监控平台
  • prometheus-grafana - 开源监控方案
  • alerting-oncall - 告警管理