mcpField
N
new-relic

new-relic

github.com/bagelholeクラウド・DevOps1.2k333 回インストール23 週間前に更新
リポジトリ

new-relic について

アプリケーションやインフラを監視するチーム向けの New Relic オブザーバビリティスキルです。監視エージェントの導入、テレメトリ収集、クエリやダッシュボード、アラートの設定方法を扱います。

主な機能

  1. 01アプリケーションとインフラの監視
  2. 02APM エージェントの設定
  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 エージェント用のアプリケーションへのアクセス
  • ホストエージェント用のインフラストラクチャへのアクセス

インフラストラクチャエージェント

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 エージェント

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'}
)
カスタムスパン
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

よくある問題

問題:データが表示されない

問題:エージェントから New Relic にデータが報告されていません 解決策:ライセンスキーを確認し、ネットワーク接続を確認して、エージェントログを確認してください

問題:トランザクションが欠落している

問題:一部のトランザクションが取得されていません 解決策:計装の対象範囲を確認し、フレームワークがサポートされていることを確認してください

問題:オーバーヘッドが高い

問題:APM エージェントがパフォーマンスに影響しています 解決策:サンプリングレートを調整し、不要な機能を無効にしてください

ベストプラクティス

  • 意味のあるアプリケーション名を使用します
  • サービス間で分散トレーシングを実装します
  • 依存関係を可視化するサービスマップを設定します
  • 適切なしきい値でアラートを設定します
  • ビジネスコンテキストにカスタム属性を使用します
  • 相関関係を把握するためにコンテキスト内のログを実装します
  • サービスをグループ化するためにワークロードを設定します
  • 使用されていないダッシュボードとアラートを定期的に見直します

関連スキル

コメント