mcpField
N
new-relic

new-relic

github.com/bagelhole云与 DevOps1.2k333 次安装23 周前更新
代码仓库

关于 new-relic

面向应用与基础设施团队的 New Relic 可观测性技能,提供部署监控代理、采集遥测数据及配置查询、仪表板和告警的指导。

主要功能

  1. 01应用与基础设施监控
  2. 02APM Agent 配置
  3. 03分布式追踪与自定义埋点
  4. 04NRQL 查询示例
  5. 05仪表板与告警配置
  6. 06日志关联与转发

适用场景

  1. 01为应用配置 APM 监控
  2. 02排查基础设施健康问题
  3. 03创建自定义仪表板和告警
  4. 04关联日志、指标与追踪数据

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill new-relic

安装后在 Claude Code 中输入/new-relic确认已加载。

详细介绍

New Relic

使用 New Relic 可观测性平台监控应用程序和基础设施。

何时使用此技能

在以下情况下使用此技能:

  • 实现全栈可观测性
  • 为应用程序设置 APM
  • 监控基础设施运行状况
  • 创建自定义仪表板和警报
  • 实现分布式追踪

前提条件

  • New Relic 账户和许可证密钥
  • 用于 APM Agent 的应用程序访问权限
  • 用于主机 Agent 的基础设施访问权限

Infrastructure Agent

Linux 安装
# Add repository and install
curl -Ls https://download.newrelic.com/install/newrelic-cli/scripts/install.sh | bash

# Configure license key
sudo NEW_RELIC_API_KEY=<YOUR_API_KEY> NEW_RELIC_ACCOUNT_ID=<ACCOUNT_ID> /usr/local/bin/newrelic install

# Or manual configuration
echo "license_key: YOUR_LICENSE_KEY" | sudo tee -a /etc/newrelic-infra.yml
sudo systemctl start newrelic-infra
Docker
# 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
Kubernetes
# 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

APM Agent

Node.js
// 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'
  }
};
# Install agent
npm install newrelic

# Run application
NEW_RELIC_LICENSE_KEY=xxx node -r newrelic app.js
Python
# 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
# Install agent
pip install newrelic

# Generate config file
newrelic-admin generate-config YOUR_LICENSE_KEY newrelic.ini

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

# Or with gunicorn
NEW_RELIC_CONFIG_FILE=newrelic.ini newrelic-admin run-program gunicorn app:app
Java
# Download agent
curl -O https://download.newrelic.com/newrelic/java-agent/newrelic-agent/current/newrelic-java.zip
unzip newrelic-java.zip

# Configure newrelic.yml
# license_key: YOUR_LICENSE_KEY
# app_name: My Application

# Run with agent
java -javaagent:/path/to/newrelic.jar -jar myapp.jar
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!"))
}

自定义埋点

自定义事件
import newrelic.agent

# Record custom event
newrelic.agent.record_custom_event('OrderPlaced', {
    'order_id': '12345',
    'amount': 99.99,
    'customer_id': 'cust_001'
})
自定义指标
import newrelic.agent

# Record custom metric
newrelic.agent.record_custom_metric('Custom/OrderValue', 99.99)

# With attributes
newrelic.agent.record_custom_metric('Custom/ProcessingTime', 
    processing_time, 
    {'unit': 'milliseconds'}
)
自定义 Span
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
with newrelic.agent.FunctionTrace(name='custom_operation'):
    # Traced code
    pass

NRQL 查询

基本查询
-- 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
高级查询
-- 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

仪表板

仪表板 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"
              }
            ]
          }
        }
      ]
    }
  ]
}

警报

警报条件(NRQL)
{
  "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"
    }
  ]
}
警报策略
{
  "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"
        }
      ]
    }
  ]
}

上下文中的日志

Python 配置
# newrelic.ini
[newrelic]
application_logging.enabled = true
application_logging.forwarding.enabled = true
application_logging.metrics.enabled = true
application_logging.local_decorating.enabled = true
日志转发
# newrelic-infra.yml
log:
  - name: application-logs
    file: /var/log/myapp/*.log
    attributes:
      service: myapp
      environment: production

常见问题

问题:未显示数据

问题:Agent 未向 New Relic 报告数据
解决方案:验证许可证密钥,检查网络连接,并查看 Agent 日志

问题:缺少事务

问题:未捕获某些事务
解决方案:检查埋点覆盖范围,并确认框架支持情况

问题:开销过高

问题:APM Agent 影响性能
解决方案:调整采样率,禁用不必要的功能

最佳实践

  • 使用有意义的应用程序名称
  • 在各项服务之间实现分布式追踪
  • 设置服务映射以可视化依赖关系
  • 配置适当的警报阈值
  • 使用自定义属性提供业务上下文
  • 实现上下文中的日志以便关联
  • 设置工作负载以对服务进行分组
  • 定期检查未使用的仪表板和警报

相关技能

评论

支持 Markdown