Ruby アプリケーション向け New Relic APM 設定ガイド

Ruby アプリケーションでの New Relic APM 導入は、Ruby エコシステムの豊富なフレームワークとライブラリとの深い統合を通じて、詳細なパフォーマンス監視を実現します。Ruby エージェントは、Rails の規約に従った自動計測により、既存のコードを最小限の変更で監視対象にできます。

Ruby エージェントの特徴

Ruby エージェントの概要

New Relic Ruby エージェントは、Ruby の動的メソッド呼び出しとメタプログラミング機能を活用して、既存のコードを最小限の変更で監視対象にできます。Rails、Sinatra などの主要フレームワークとの自動統合により、MVC パターンの各層を包括的に監視します。

エージェントは以下の情報を自動的に収集します:

  • HTTP リクエストとレスポンスの処理時間
  • Active Record のデータベース操作
  • コントローラーアクションとビューのレンダリング時間
  • エラーとスタックトレース

事前準備

システム要件

  • 推奨: Ruby 3.2+ (最新の性能最適化対応)
  • 最小要件: Ruby 3.0+ (セキュリティサポート期間内)
  • フレームワーク: Rails 7.0+ 推奨、Sinatra 3.0+ 推奨
  • 注意: Ruby 2.7以前は非推奨(セキュリティリスク)
  • Web サーバー: Puma、Unicorn、Passenger、Thin
  • プラットフォーム: Linux、macOS、Windows(WSL2)

Ruby エージェントを導入する前に、以下の要件を確認してください:

  • Ruby 2.7 以降(Ruby 3.x 推奨)
  • Rails 6.0 以降、Sinatra 2.0 以降
  • Web サーバー: Puma、Unicorn、Passenger、Thin
  • Bundler を使用した依存関係管理

New Relic アカウントの準備

New Relic のアカウント作成とライセンスキーの取得が必要です。アカウント作成後、「APM & Services」から新しいアプリケーションを追加し、Ruby を選択してライセンスキーを取得してください。

エージェントのインストール

Gemfile への追加

ruby
# Gemfile
gem 'newrelic_rpm'

Bundle install の実行

bash
bundle install

Rails アプリケーションでは、gem の追加だけで基本的な監視が自動的に有効になります。

基本設定

newrelic.yml 設定ファイルの生成

bash
# 設定ファイルの生成
bundle exec newrelic install YOUR_LICENSE_KEY "My Ruby Application"

newrelic.yml の基本設定

yaml
# config/newrelic.yml
common: &default_settings
  license_key: '<%= ENV["NEW_RELIC_LICENSE_KEY"] %>'
  app_name: My Ruby Application

production:
  <<: *default_settings
  app_name: My Ruby Application (Production)
  log_level: info
  
development:
  <<: *default_settings
  app_name: My Ruby Application (Development)
  log_level: debug

test:
  <<: *default_settings
  app_name: My Ruby Application (Test)
  monitor_mode: false

環境変数による設定(推奨)

セキュリティ強化のため、本番環境では環境変数を使用します:

bash
# セキュアな環境変数設定
export NEW_RELIC_LICENSE_KEY="your_license_key_here"
export NEW_RELIC_APP_NAME="MyRubyApp (Production)"
export NEW_RELIC_ENVIRONMENT="production"
export NEW_RELIC_LOG_LEVEL="info"
export NEW_RELIC_DISTRIBUTED_TRACING_ENABLED="true"
export NEW_RELIC_HIGH_SECURITY="true"  # セキュリティ強化モード
export NEW_RELIC_CAPTURE_PARAMS="false"  # 機密パラメータ保護

.env ファイルでの管理(開発環境)

開発環境では .env ファイルを使用して環境変数を管理:

bash
# .env ファイル(.gitignoreに追加必須)
NEW_RELIC_LICENSE_KEY=your_license_key_here
NEW_RELIC_APP_NAME="MyRubyApp (Development)"
NEW_RELIC_ENVIRONMENT=development
NEW_RELIC_LOG_LEVEL=debug
NEW_RELIC_MONITOR_MODE=false
NEW_RELIC_DEVELOPER_MODE=true

# セキュリティ設定
NEW_RELIC_HIGH_SECURITY=false
NEW_RELIC_CAPTURE_PARAMS=true  # 開発環境でのみ有効

dotenv-rails での読み込み

ruby
# Gemfile
gem 'dotenv-rails', groups: [:development, :test]

# config/application.rb
if Rails.env.development? || Rails.env.test?
  require 'dotenv/rails-now'
end

フレームワーク別設定

Rails アプリケーション

Rails では、gem をインストールするだけで自動的に監視が開始されます。追加の設定により、さらに詳細な情報を収集できます:

application.rb での設定

ruby
# config/application.rb
module MyApp
  class Application < Rails::Application
    # New Relic の初期化設定(任意)
    config.after_initialize do
      if defined?(NewRelic::Agent)
        NewRelic::Agent.manual_start
      end
    end
  end
end

コントローラーでの基本的なカスタム計測

ruby
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :set_newrelic_user_attributes
  
  private
  
  def set_newrelic_user_attributes
    if current_user && defined?(NewRelic::Agent)
      NewRelic::Agent.set_user_attributes(
        user_id: current_user.id,
        user_name: current_user.name,
        user_email: current_user.email
      )
    end
  end
end

Sinatra アプリケーション

ruby
# app.rb
require 'sinatra'
require 'newrelic_rpm'

class MyApp < Sinatra::Base
  configure do
    NewRelic::Agent.manual_start(
      app_name: 'My Sinatra App',
      license_key: ENV['NEW_RELIC_LICENSE_KEY']
    )
  end
  
  get '/api/users/:id' do
    content_type :json
    user = User.find(params[:id])
    user.to_json
  end
end

カスタム計測の基本

メトリクスの記録

重要なビジネス指標を記録する場合:

ruby
# カスタムメトリクスの記録
if defined?(NewRelic::Agent)
  NewRelic::Agent.record_custom_metric('Custom/Revenue', order.total_amount)
  NewRelic::Agent.record_custom_metric('Custom/OrdersProcessed', 1)
  
  # カスタムイベントの記録
  NewRelic::Agent.record_custom_event('OrderCreated', {
    order_id: order.id,
    customer_id: order.customer_id,
    total_amount: order.total_amount
  })
end

関数レベルの監視

ruby
class OrdersController < ApplicationController
  def create
    @order = NewRelic::Agent::MethodTracer.trace_execution_scoped("Custom/Orders/Create") do
      Order.create(order_params)
    end
    
    if @order.persisted?
      # 成功メトリクスの記録
      NewRelic::Agent.record_custom_metric("Custom/Orders/Created", 1)
      redirect_to @order, notice: 'Order was successfully created.'
    else
      render :new
    end
  end
end

監視データの確認

New Relic UI でのデータ確認

エージェント導入後、数分で New Relic のダッシュボードにデータが表示されます。確認できる主要な情報:

  • 概要: アプリケーションの全体的なパフォーマンス
  • トランザクション: 各コントローラーアクションの処理時間
  • データベース: Active Record クエリの実行時間
  • エラー: Ruby 例外とエラーの詳細

基本的なメトリクス

自動的に収集される基本メトリクス:

  • 平均レスポンス時間
  • スループット(RPM: Requests Per Minute)
  • エラー率
  • Apdex スコア(ユーザー満足度指標)

よくある問題と解決方法

エージェントが動作しない場合

  1. gem の確認: bundle list | grep newrelic でgemがインストールされているか確認
  2. ライセンスキー: 設定ファイルに正しいキーが記載されているか確認
  3. Rails環境: 本番環境で monitor_mode が有効になっているか確認
  4. ログの確認: log/newrelic_agent.log でエラーを確認

パフォーマンスへの影響を最小化

本番環境での設定例:

yaml
production:
  <<: *default_settings
  # パフォーマンス最適化設定
  transaction_tracer:
    transaction_threshold: 1.0
    top_n: 20
  error_collector:
    max_stack_trace_lines: 50

セキュリティ設定

機密情報を保護するための基本設定:

yaml
production:
  <<: *default_settings
  # セキュリティ設定
  capture_params: false
  transaction_tracer:
    record_sql: obfuscated
  attributes:
    exclude:
      - request.parameters.password
      - request.parameters.credit_card

Docker での設定

Docker での設定

セキュリティ強化された Docker 設定例:

dockerfile
# セキュリティ強化されたマルチステージビルド
FROM ruby:3.2-alpine as builder

# セキュリティベストプラクティス:非rootユーザーの作成
RUN addgroup -g 1001 -S appuser && \
    adduser -u 1001 -S appuser -G appuser

# 依存関係のインストール
WORKDIR /app
COPY Gemfile Gemfile.lock ./

# 開発依存関係を除外して高速化
RUN bundle config set --local deployment 'true' && \
    bundle config set --local without 'development test' && \
    bundle install --jobs 4 --retry 3

# 本番イメージ
FROM ruby:3.2-alpine

# 非rootユーザーの作成
RUN addgroup -g 1001 -S appuser && \
    adduser -u 1001 -S appuser -G appuser

# 必要なシステムパッケージのインストール
RUN apk add --no-cache \
    postgresql-client \
    tzdata

# 作業ディレクトリの設定
WORKDIR /app

# Gemのコピー
COPY --from=builder /usr/local/bundle /usr/local/bundle
COPY --chown=appuser:appuser . .

# 非rootユーザーに切り替え
USER appuser

# セキュリティ強化設定
ENV NEW_RELIC_HIGH_SECURITY=true
ENV NEW_RELIC_CAPTURE_PARAMS=false
ENV NEW_RELIC_ENABLED=true
ENV NEW_RELIC_LOG_LEVEL=info
ENV RAILS_ENV=production

# ヘルスチェック
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD curl -f http://localhost:3000/health || exit 1

# Rails アプリケーション起動
EXPOSE 3000
CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"]

Docker Compose 設定例

yaml
version: '3.8'
services:
  ruby-app:
    build: .
    environment:
      - NEW_RELIC_LICENSE_KEY=${NEW_RELIC_LICENSE_KEY}
      - NEW_RELIC_APP_NAME=MyRubyApp (Docker)
      - NEW_RELIC_ENVIRONMENT=production
      - NEW_RELIC_HIGH_SECURITY=true
      - NEW_RELIC_DISTRIBUTED_TRACING_ENABLED=true
      - DATABASE_URL=${DATABASE_URL}
    ports:
      - "3000:3000"
    security_opt:
      - no-new-privileges:true
    read_only: true
    tmpfs:
      - /tmp
      - /app/tmp
    user: "1001:1001"  # 非rootユーザー
    depends_on:
      - postgres
      - redis
  
  postgres:
    image: postgres:15-alpine
    environment:
      - POSTGRES_DB=myapp_production
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    security_opt:
      - no-new-privileges:true

volumes:
  postgres_data:

Kubernetes での設定

セキュリティ強化された Kubernetes デプロイメント:

yaml
# Secret リソース
apiVersion: v1
kind: Secret
metadata:
  name: newrelic-secret
  namespace: production
type: Opaque
data:
  license-key: <base64_encoded_license_key>
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: ruby-app-config
  namespace: production
data:
  NEW_RELIC_APP_NAME: "MyRubyApp (K8s)"
  NEW_RELIC_ENVIRONMENT: "production"
  NEW_RELIC_HIGH_SECURITY: "true"
  NEW_RELIC_DISTRIBUTED_TRACING_ENABLED: "true"
  NEW_RELIC_LOG_LEVEL: "info"
  RAILS_ENV: "production"
  RAILS_MAX_THREADS: "5"
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ruby-app
  namespace: production
  labels:
    app: ruby-app
    version: v1.0.0
spec:
  replicas: 3
  selector:
    matchLabels:
      app: ruby-app
  template:
    metadata:
      labels:
        app: ruby-app
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "3000"
        prometheus.io/path: "/metrics"
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 1001
        runAsGroup: 1001
        fsGroup: 1001
      containers:
      - name: app
        image: myrubyapp:latest
        imagePullPolicy: Always
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities:
            drop:
            - ALL
        env:
        - name: NEW_RELIC_LICENSE_KEY
          valueFrom:
            secretKeyRef:
              name: newrelic-secret
              key: license-key
        envFrom:
        - configMapRef:
            name: ruby-app-config
        ports:
        - containerPort: 3000
          name: http
          protocol: TCP
        resources:
          requests:
            memory: "512Mi"
            cpu: "250m"
          limits:
            memory: "1Gi"
            cpu: "500m"
        readinessProbe:
          httpGet:
            path: /health
            port: 3000
          initialDelaySeconds: 15
          periodSeconds: 10
          timeoutSeconds: 5
        livenessProbe:
          httpGet:
            path: /health
            port: 3000
          initialDelaySeconds: 30
          periodSeconds: 15
          timeoutSeconds: 5
        volumeMounts:
        - name: tmp-volume
          mountPath: /tmp
        - name: app-tmp-volume
          mountPath: /app/tmp
      volumes:
      - name: tmp-volume
        emptyDir:
          sizeLimit: 100Mi
      - name: app-tmp-volume
        emptyDir:
          sizeLimit: 100Mi
      restartPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
  name: ruby-app-service
  namespace: production
  labels:
    app: ruby-app
spec:
  selector:
    app: ruby-app
  ports:
  - protocol: TCP
    port: 80
    targetPort: 3000
    name: http
  type: ClusterIP
---
# HorizontalPodAutoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: ruby-app-hpa
  namespace: production
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: ruby-app
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80

Capistrano でのデプロイメント連携

ruby
# config/deploy.rb
after 'deploy:updated', 'newrelic:notice_deployment'

namespace :newrelic do
  desc 'Notify New Relic of deployment'
  task :notice_deployment do
    on roles(:app) do
      within release_path do
        execute :bundle, :exec, 'newrelic', 'deployments', 
                '--revision', fetch(:current_revision),
                '--description', "Deployed at #{Time.current}"
      end
    end
  end
end

トラブルシューティング

診断フローチャート

一般的な問題と解決方法

1. データが New Relic に表示されない

症状: Rails アプリケーションが New Relic ダッシュボードに表示されない

診断用ヘルスチェック:

ruby
# app/controllers/health_controller.rb
class HealthController < ApplicationController
  def newrelic_status
    diagnostics = NewRelicDiagnostics.new
    render json: diagnostics.run_full_check
  end
end

# lib/new_relic_diagnostics.rb
class NewRelicDiagnostics
  def run_full_check
    {
      gem_loaded: gem_loaded_check,
      agent_status: agent_status_check,
      configuration: configuration_check,
      connectivity: connectivity_check,
      framework_integration: framework_integration_check,
      environment: environment_check
    }
  end

  private

  def gem_loaded_check
    {
      newrelic_rpm_loaded: defined?(NewRelic::Agent),
      version: defined?(NewRelic::VERSION) ? NewRelic::VERSION::STRING : 'N/A'
    }
  end

  def agent_status_check
    return { status: 'not_loaded' } unless defined?(NewRelic::Agent)
    
    {
      started: NewRelic::Agent.agent.started?,
      connected: NewRelic::Agent.agent.connected?,
      monitor_mode: NewRelic::Agent.config[:monitor_mode]
    }
  end

  def configuration_check
    return { status: 'agent_not_loaded' } unless defined?(NewRelic::Agent)
    
    config = NewRelic::Agent.config
    {
      app_name: config[:app_name],
      license_key_present: config[:license_key].present?,
      license_key_format: config[:license_key]&.length == 40,
      environment: config[:environment],
      log_level: config[:log_level],
      high_security: config[:high_security]
    }
  end

  def connectivity_check
    return { status: 'agent_not_loaded' } unless defined?(NewRelic::Agent)
    
    begin
      # 接続テスト(簡易版)
      {
        host: NewRelic::Agent.config[:host],
        port: NewRelic::Agent.config[:port],
        ssl: NewRelic::Agent.config[:ssl],
        proxy_host: NewRelic::Agent.config[:proxy_host]
      }
    rescue => e
      { error: e.message }
    end
  end

  def framework_integration_check
    {
      rails_version: defined?(Rails) ? Rails.version : 'N/A',
      sinatra_detected: defined?(Sinatra),
      rack_version: defined?(Rack) ? Rack.version : 'N/A',
      middleware_loaded: rails_middleware_check
    }
  end

  def environment_check
    {
      ruby_version: RUBY_VERSION,
      rails_env: defined?(Rails) ? Rails.env : ENV['RACK_ENV'] || 'unknown',
      bundler_version: defined?(Bundler) ? Bundler::VERSION : 'N/A',
      pid: Process.pid
    }
  end

  def rails_middleware_check
    return false unless defined?(Rails) && Rails.application

    Rails.application.middleware.middlewares.any? do |middleware|
      middleware.to_s.include?('NewRelic')
    end
  end
end

2. Rails でトランザクションが記録されない

症状: コントローラーのアクションが New Relic に表示されない

解決方法:

ruby
# config/application.rb で明示的にNew Relicを有効化
module MyApp
  class Application < Rails::Application
    # New Relic の明示的初期化
    config.after_initialize do
      if defined?(NewRelic::Agent) && !NewRelic::Agent.agent.started?
        NewRelic::Agent.manual_start
      end
    end
  end
end

# コントローラーで明示的なインスツルメンテーション
class ApplicationController < ActionController::Base
  # New Relic インスツルメンテーションの強制有効化
  newrelic_ignore_apdex if respond_to?(:newrelic_ignore_apdex)
  
  around_action :ensure_newrelic_transaction
  
  private
  
  def ensure_newrelic_transaction
    if defined?(NewRelic::Agent)
      # トランザクションが開始されていない場合は手動で開始
      unless NewRelic::Agent.current_transaction
        NewRelic::Agent.start_transaction(
          name: "Controller/#{controller_name}##{action_name}",
          category: :controller
        )
      end
    end
    
    yield
    
  ensure
    # カスタム属性の追加
    if defined?(NewRelic::Agent)
      NewRelic::Agent.add_custom_attributes(
        controller: controller_name,
        action: action_name,
        request_method: request.request_method,
        response_status: response.status
      )
    end
  end
end

3. Sidekiq ジョブが監視されない

症状: バックグラウンドジョブが New Relic に表示されない

解決方法:

ruby
# config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
  # New Relic Sidekiq統合の強制有効化
  if defined?(NewRelic::Agent)
    require 'newrelic_rpm'
    require 'newrelic/agent/instrumentation/sidekiq'
  end
end

# ワーカークラスでの明示的な統合
class MyWorker
  include Sidekiq::Worker
  
  # New Relic統合の明示的な追加
  if defined?(NewRelic::Agent::Instrumentation::Sidekiq)
    include NewRelic::Agent::Instrumentation::Sidekiq
  end
  
  def perform(*args)
    # New Relicトランザクションの手動開始(フォールバック)
    transaction_name = "SidekiqJob/#{self.class.name}"
    
    if defined?(NewRelic::Agent)
      NewRelic::Agent.set_transaction_name('Background', transaction_name)
      
      NewRelic::Agent.add_custom_attributes(
        job_class: self.class.name,
        job_args_count: args.length,
        sidekiq_queue: self.class.get_sidekiq_options['queue']
      )
    end
    
    # 実際のジョブ処理
    process_job(*args)
    
  rescue => e
    NewRelic::Agent.notice_error(e) if defined?(NewRelic::Agent)
    raise
  end
  
  private
  
  def process_job(*args)
    # ジョブの実装
  end
end

4. メモリリークの検出と対処

症状: アプリケーションのメモリ使用量が継続的に増加

監視とアラート設定:

ruby
# config/initializers/memory_monitoring.rb
if Rails.env.production?
  # メモリ監視スレッドの開始
  Thread.new do
    loop do
      begin
        # プロセスメモリ情報の取得
        if RUBY_PLATFORM =~ /linux/
          status_file = "/proc/#{Process.pid}/status"
          if File.exist?(status_file)
            status = File.read(status_file)
            
            # VmRSS(物理メモリ)の取得
            if match = status.match(/VmRSS:\s+(\d+)\s+kB/)
              rss_kb = match[1].to_i
              rss_mb = rss_kb / 1024.0
              
              NewRelic::Agent.record_custom_metric('Custom/Memory/RSS_MB', rss_mb)
              
              # メモリアラート(1GB超過時)
              if rss_mb > 1024
                NewRelic::Agent.record_custom_event('MemoryAlert', {
                  pid: Process.pid,
                  memory_mb: rss_mb,
                  alert_level: 'high',
                  timestamp: Time.now.to_i
                })
              end
            end
          end
        end
        
        # Ruby GC統計の記録
        gc_stat = GC.stat
        NewRelic::Agent.record_custom_metric('Custom/GC/Heap/LiveObjects', gc_stat[:heap_live_slots])
        NewRelic::Agent.record_custom_metric('Custom/GC/Heap/FreeObjects', gc_stat[:heap_free_slots])
        NewRelic::Agent.record_custom_metric('Custom/GC/Collections/Major', gc_stat[:major_gc_count])
        NewRelic::Agent.record_custom_metric('Custom/GC/Collections/Minor', gc_stat[:minor_gc_count])
        
        # ObjectSpace統計(開発環境のみ)
        if Rails.env.development?
          ObjectSpace.each_object.group_by(&:class).each do |klass, objects|
            next if objects.size < 100
            NewRelic::Agent.record_custom_metric(
              "Custom/ObjectSpace/#{klass.name.gsub('::', '/')}", 
              objects.size
            )
          end
        end
        
        sleep 60 # 1分間隔
      rescue => e
        Rails.logger.error "Memory monitoring error: #{e.message}"
        sleep 300 # エラー時は5分待機
      end
    end
  end
end

パフォーマンス最適化のトラブルシューティング

ruby
# lib/performance_diagnostics.rb
class PerformanceDiagnostics
  include NewRelic::Agent::MethodTracer
  
  def self.analyze_slow_queries
    # スロークエリの分析
    if defined?(ActiveRecord)
      subscriber = ActiveSupport::Notifications.subscribe('sql.active_record') do |name, start, finish, id, payload|
        duration = finish - start
        
        if duration > 1.0  # 1秒以上のクエリ
          NewRelic::Agent.record_custom_event('SlowQuery', {
            sql: payload[:sql].truncate(500),
            duration_seconds: duration,
            connection_id: payload[:connection_id],
            binds: payload[:binds]&.map(&:value)&.to_s&.truncate(200)
          })
        end
      end
    end
  end
  
  def self.monitor_action_view_rendering
    # ビュー描画時間の監視
    ActiveSupport::Notifications.subscribe('render_template.action_view') do |name, start, finish, id, payload|
      duration = finish - start
      
      if duration > 0.5  # 0.5秒以上の描画
        NewRelic::Agent.record_custom_event('SlowViewRender', {
          template: payload[:identifier],
          duration_seconds: duration,
          layout: payload[:layout]
        })
      end
    end
  end
  
  def self.detect_n_plus_one_queries
    # N+1クエリの検出(簡易版)
    query_counts = Hash.new(0)
    
    ActiveSupport::Notifications.subscribe('sql.active_record') do |name, start, finish, id, payload|
      # 同一SQLの実行回数をカウント
      sql_pattern = payload[:sql].gsub(/\d+/, '?').gsub(/'[^']*'/, '?')
      query_counts[sql_pattern] += 1
      
      # 同一パターンのクエリが多数実行された場合
      if query_counts[sql_pattern] > 10
        NewRelic::Agent.record_custom_event('NPlusOneQuery', {
          sql_pattern: sql_pattern.truncate(300),
          execution_count: query_counts[sql_pattern]
        })
      end
    end
  end
end

# config/initializers/performance_diagnostics.rb
if Rails.env.production?
  PerformanceDiagnostics.analyze_slow_queries
  PerformanceDiagnostics.monitor_action_view_rendering
end

if Rails.env.development?
  PerformanceDiagnostics.detect_n_plus_one_queries
end

ログ分析とデバッグモード

ruby
# config/newrelic.yml でのデバッグ設定
development:
  <<: *default_settings
  app_name: My Ruby Application (Development)
  log_level: debug
  developer_mode: true
  
  # 詳細ログの有効化
  audit_log:
    enabled: true
    path: log/newrelic_audit.log
  
  # デバッグ用詳細設定
  debug:
    raw_transaction_trace_data: true
    record_transaction_trace_segments: true
    explain_threshold: 0.0
    record_raw_web_transaction_sql: true

New Relic Ruby APM 設定パラメータ一覧

New Relic Ruby APMエージェントで使用可能な全設定パラメータを機能別に分類し、包括的に整理した表を以下に示します。

基本設定パラメータ

パラメータ名デフォルト値タイプ環境変数名説明
license_key空文字列StringNEW_RELIC_LICENSE_KEYNew Relicアカウントのライセンスキー(必須)
app_name環境名String/ListNEW_RELIC_APP_NAMENew Relic UIに表示されるアプリケーション名(セミコロン区切りで複数指定可能)
agent_enabledtrueBooleanNEW_RELIC_AGENT_ENABLEDエージェント全体の有効/無効制御
monitor_modetrueBooleanNEW_RELIC_MONITOR_MODEデータ送信の有効/無効(falseでオフライン開発モード)
log_levelinfoStringNEW_RELIC_LOG_LEVELログレベル設定(debug, info, warn, error)
log_file_namenewrelic_agent.logStringNEW_RELIC_LOG_FILE_NAMEログファイル名
log_file_pathlog/StringNEW_RELIC_LOG_FILE_PATHログファイルのパス

トランザクション監視設定

パラメータ名デフォルト値タイプ環境変数名説明
transaction_tracer.enabledtrueBooleanNEW_RELIC_TRANSACTION_TRACER_ENABLEDトランザクショントレースの有効/無効
transaction_tracer.transaction_thresholdapdex_fFloat/StringNEW_RELIC_TRANSACTION_TRACER_TRANSACTION_THRESHOLDトランザクショントレースの閾値(秒)、デフォルトはApdex T の4倍
transaction_tracer.explain_enabledtrueBooleanNEW_RELIC_TRANSACTION_TRACER_EXPLAIN_ENABLEDSQL実行計画の収集有効/無効
transaction_tracer.explain_threshold0.5FloatNEW_RELIC_TRANSACTION_TRACER_EXPLAIN_THRESHOLDSQL実行計画収集の閾値(秒)
transaction_tracer.record_sqlobfuscatedStringNEW_RELIC_TRANSACTION_TRACER_RECORD_SQLSQL記録方式(raw, obfuscated, off)
transaction_tracer.limit_segments4000IntegerNEW_RELIC_TRANSACTION_TRACER_LIMIT_SEGMENTSトランザクショントレースの最大セグメント数
transaction_events.enabledtrueBooleanNEW_RELIC_TRANSACTION_EVENTS_ENABLEDトランザクションイベントの収集有効/無効
transaction_events.max_samples_stored1200IntegerNEW_RELIC_TRANSACTION_EVENTS_MAX_SAMPLES_STORED保存する最大トランザクションイベント数

エラー収集設定

パラメータ名デフォルト値タイプ環境変数名説明
error_collector.enabledtrueBooleanNEW_RELIC_ERROR_COLLECTOR_ENABLEDエラー収集の有効/無効
error_collector.capture_eventstrueBooleanNEW_RELIC_ERROR_COLLECTOR_CAPTURE_EVENTSエラーイベントの収集有効/無効
error_collector.max_event_samples_stored100IntegerNEW_RELIC_ERROR_COLLECTOR_MAX_EVENT_SAMPLES_STORED保存する最大エラーイベント数
error_collector.ignore_classes空配列ArrayNEW_RELIC_ERROR_COLLECTOR_IGNORE_CLASSES無視するエラークラス(カンマ区切り)
error_collector.ignore_messages空ハッシュHashNEW_RELIC_ERROR_COLLECTOR_IGNORE_MESSAGESエラーメッセージによる無視設定
error_collector.ignore_status_codes空文字列StringNEW_RELIC_ERROR_COLLECTOR_IGNORE_STATUS_CODES無視するHTTPステータスコード
error_collector.expected_classes空配列ArrayNEW_RELIC_ERROR_COLLECTOR_EXPECTED_CLASSES期待されるエラークラス
error_collector.expected_messages空ハッシュHashNEW_RELIC_ERROR_COLLECTOR_EXPECTED_MESSAGES期待されるエラーメッセージ
error_collector.expected_status_codes空文字列StringNEW_RELIC_ERROR_COLLECTOR_EXPECTED_STATUS_CODES期待されるHTTPステータスコード

ブラウザ監視設定

パラメータ名デフォルト値タイプ環境変数名説明
browser_monitoring.auto_instrumenttrueBooleanNEW_RELIC_BROWSER_MONITORING_AUTO_INSTRUMENTブラウザJavaScriptの自動挿入
browser_monitoring.content_security_policy_noncetrueBooleanNEW_RELIC_BROWSER_MONITORING_CONTENT_SECURITY_POLICY_NONCECSP nonceの自動適用(Rails 5.2以降)
browser_monitoring.attributes.enabledfalseBooleanNEW_RELIC_BROWSER_MONITORING_ATTRIBUTES_ENABLEDブラウザ監視での属性収集
browser_monitoring.attributes.exclude空配列ArrayNEW_RELIC_BROWSER_MONITORING_ATTRIBUTES_EXCLUDEブラウザ監視から除外する属性(ワイルドカード*対応)
browser_monitoring.attributes.include空配列ArrayNEW_RELIC_BROWSER_MONITORING_ATTRIBUTES_INCLUDEブラウザ監視に含める属性(ワイルドカード*対応)

分散トレーシング設定

パラメータ名デフォルト値タイプ環境変数名説明
distributed_tracing.enabledtrueBooleanNEW_RELIC_DISTRIBUTED_TRACING_ENABLED分散トレーシングの有効/無効(v8.0.0以降はデフォルトで有効)
span_events.enabledtrueBooleanNEW_RELIC_SPAN_EVENTS_ENABLEDスパンイベントの収集有効/無効
span_events.max_samples_stored1000IntegerNEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED保存する最大スパンイベント数(1-10000、AI監視では10000推奨)

アプリケーションログ設定

パラメータ名デフォルト値タイプ環境変数名説明
application_logging.enabledtrueBooleanNEW_RELIC_APPLICATION_LOGGING_ENABLEDログ装飾と収集の有効/無効
application_logging.forwarding.enabledtrueBooleanNEW_RELIC_APPLICATION_LOGGING_FORWARDING_ENABLEDログレコードの転送有効/無効
application_logging.forwarding.log_leveldebugStringNEW_RELIC_APPLICATION_LOGGING_FORWARDING_LOG_LEVEL転送する最小ログレベル
application_logging.local_decorating.enabledfalseBooleanNEW_RELIC_APPLICATION_LOGGING_LOCAL_DECORATING_ENABLEDローカルログ装飾の有効/無効
application_logging.metrics.enabledtrueBooleanNEW_RELIC_APPLICATION_LOGGING_METRICS_ENABLEDログメトリクス収集の有効/無効

セキュリティ設定

パラメータ名デフォルト値タイプ環境変数名説明
high_securityfalseBooleanNEW_RELIC_HIGH_SECURITY高セキュリティモードの有効/無効
strip_exception_messages.enabledhigh_security設定に依存BooleanNEW_RELIC_STRIP_EXCEPTION_MESSAGES_ENABLED例外メッセージの削除
capture_paramsfalseBooleanNEW_RELIC_CAPTURE_PARAMSHTTPリクエストパラメータの収集
ignored_params空配列ArrayNEW_RELIC_IGNORED_PARAMS除外するパラメータ名(カンマ区切り)
security.agent.enabledfalseBooleanNEW_RELIC_SECURITY_AGENT_ENABLEDセキュリティエージェント(IAST)の有効/無効
security.enabledfalseBooleanNEW_RELIC_SECURITY_ENABLEDセキュリティ機能の有効/無効
security.modeIASTStringNEW_RELIC_SECURITY_MODEセキュリティモード(IAST/RASP)
security.detection.rci.enabledtrueBooleanNEW_RELIC_SECURITY_DETECTION_RCI_ENABLEDRCE脆弱性検出の有効/無効
security.detection.rxss.enabledtrueBooleanNEW_RELIC_SECURITY_DETECTION_RXSS_ENABLEDRXSS脆弱性検出の有効/無効

パフォーマンス設定

パラメータ名デフォルト値タイプ環境変数名説明
agent_limits.transaction_traces_nodes2000IntegerNEW_RELIC_AGENT_LIMITS_TRANSACTION_TRACES_NODESトランザクショントレースの最大ノード数
agent_limits.sql_query_length_maximum16384IntegerNEW_RELIC_AGENT_LIMITS_SQL_QUERY_LENGTH_MAXIMUMSQL文の最大長
agent_limits.stack_trace_lines50IntegerNEW_RELIC_AGENT_LIMITS_STACK_TRACE_LINESスタックトレースの最大行数
code_level_metrics.enabledtrueBooleanNEW_RELIC_CODE_LEVEL_METRICS_ENABLEDソースコードレベルメトリクスの報告
slow_sql.enabledtrueBooleanNEW_RELIC_SLOW_SQL_ENABLEDスロークエリトレースの有効/無効
slow_sql.explain_enabledtransaction_tracer.explain_enabled設定に依存BooleanNEW_RELIC_SLOW_SQL_EXPLAIN_ENABLEDスロークエリでの実行計画収集
slow_sql.explain_threshold0.5FloatNEW_RELIC_SLOW_SQL_EXPLAIN_THRESHOLDスロークエリ実行計画の閾値(秒)
slow_sql.record_sqlobfuscatedStringNEW_RELIC_SLOW_SQL_RECORD_SQLスロークエリの記録方式(obfuscated, raw, none)

カスタム属性設定

パラメータ名デフォルト値タイプ環境変数名説明
attributes.enabledtrueBooleanNEW_RELIC_ATTRIBUTES_ENABLED属性収集の有効/無効
attributes.exclude空配列ArrayNEW_RELIC_ATTRIBUTES_EXCLUDE除外する属性パターン(ワイルドカード*対応)
attributes.include空配列ArrayNEW_RELIC_ATTRIBUTES_INCLUDE含める属性パターン(ワイルドカード*対応)
custom_attributes.enabledtrueBooleanNEW_RELIC_CUSTOM_ATTRIBUTES_ENABLEDカスタム属性の送信有効/無効
custom_insights_events.enabledtrueBooleanNEW_RELIC_CUSTOM_INSIGHTS_EVENTS_ENABLEDカスタムイベントの収集有効/無効
custom_insights_events.max_samples_stored1200IntegerNEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STOREDカスタムイベントの最大保存数

バックグラウンドジョブ監視設定

パラメータ名デフォルト値タイプ環境変数名説明
sidekiq.capture_paramsfalseBooleanNEW_RELIC_SIDEKIQ_CAPTURE_PARAMSSidekiqジョブ引数の収集(v3.6.9-3.11.x用)
sidekiq.args.include空配列ArrayNEW_RELIC_SIDEKIQ_ARGS_INCLUDE含めるSidekiqジョブ引数のパターン(正規表現対応、v9.5.0以降)
sidekiq.args.exclude空配列ArrayNEW_RELIC_SIDEKIQ_ARGS_EXCLUDE除外するSidekiqジョブ引数のパターン(正規表現対応、v9.5.0以降)
instrumentation.sidekiqautoStringNEW_RELIC_INSTRUMENTATION_SIDEKIQSidekiqインストゥルメンテーションの制御(auto, prepend, chain, disabled)
instrumentation.delayed_jobautoStringNEW_RELIC_INSTRUMENTATION_DELAYED_JOBDelayedJobインストゥルメンテーションの制御
instrumentation.resqueautoStringNEW_RELIC_INSTRUMENTATION_RESQUEResqueインストゥルメンテーションの制御

環境検出設定

パラメータ名デフォルト値タイプ環境変数名説明
utilization.detect_awstrueBooleanNEW_RELIC_UTILIZATION_DETECT_AWSAWS環境の自動検出
utilization.detect_azuretrueBooleanNEW_RELIC_UTILIZATION_DETECT_AZUREAzure環境の自動検出
utilization.detect_dockertrueBooleanNEW_RELIC_UTILIZATION_DETECT_DOCKERDocker環境の自動検出
utilization.detect_gcptrueBooleanNEW_RELIC_UTILIZATION_DETECT_GCPGCP環境の自動検出
utilization.detect_kubernetestrueBooleanNEW_RELIC_UTILIZATION_DETECT_KUBERNETESKubernetes環境の自動検出
utilization.detect_pcftrueBooleanNEW_RELIC_UTILIZATION_DETECT_PCFPivotal Cloud Foundry環境の自動検出
serverless_mode.enabledfalseBooleanNEW_RELIC_SERVERLESS_MODE_ENABLEDサーバーレスモードの有効/無効

設定確認コマンド

現在の設定を確認するためのコマンド:

bash
# 設定ドキュメントの生成
bundle exec rake newrelic:config:docs

# エージェント状態の確認
bundle exec rake newrelic:config:all

完全な設定ファイル例

yaml
# config/newrelic.yml
common: &default_settings
  license_key: '<%= ENV["NEW_RELIC_LICENSE_KEY"] %>'
  app_name: 'My Ruby Application'
  
  # 基本設定
  agent_enabled: true
  monitor_mode: true
  log_level: 'info'
  log_file_path: 'log/'
  
  # トランザクション監視
  transaction_tracer:
    enabled: true
    transaction_threshold: 'apdex_f'
    explain_enabled: true
    explain_threshold: 0.5
    record_sql: 'obfuscated'
    limit_segments: 4000
  
  transaction_events:
    enabled: true
    max_samples_stored: 1200
  
  # エラー収集
  error_collector:
    enabled: true
    capture_events: true
    max_event_samples_stored: 100
    ignore_classes: []
    expected_classes: []
  
  # ブラウザ監視
  browser_monitoring:
    auto_instrument: true
    content_security_policy_nonce: true
    attributes:
      enabled: false
  
  # 分散トレーシング
  distributed_tracing:
    enabled: true
  
  span_events:
    enabled: true
    max_samples_stored: 2000
  
  # ログ設定
  application_logging:
    enabled: true
    forwarding:
      enabled: true
      log_level: 'debug'
    local_decorating:
      enabled: false
    metrics:
      enabled: true
  
  # セキュリティ設定
  high_security: false
  capture_params: false
  ignored_params: ['password', 'credit_card']
  strip_exception_messages:
    enabled: false
  
  # セキュリティエージェント(IAST)
  security:
    agent:
      enabled: false
    enabled: false
    mode: 'IAST'
    detection:
      rci:
        enabled: true
      rxss:
        enabled: true
  
  # パフォーマンス設定
  agent_limits:
    transaction_traces_nodes: 2000
    sql_query_length_maximum: 16384
    stack_trace_lines: 50
  
  code_level_metrics:
    enabled: true
  
  slow_sql:
    enabled: true
    explain_enabled: true
    explain_threshold: 0.5
    record_sql: 'obfuscated'
  
  # カスタム属性
  attributes:
    enabled: true
    include: ['job.sidekiq.args.*']
    exclude: ['request.headers.authorization']
  
  custom_attributes:
    enabled: true
  
  custom_insights_events:
    enabled: true
    max_samples_stored: 1200
  
  # バックグラウンドジョブ
  sidekiq:
    capture_params: false
    args:
      include: ['*']
      exclude: ['password', 'secret']
  
  instrumentation:
    sidekiq: 'auto'
    delayed_job: 'auto'
    resque: 'auto'
  
  # 環境検出
  utilization:
    detect_aws: true
    detect_azure: true
    detect_docker: true
    detect_gcp: true
    detect_kubernetes: true
    detect_pcf: true

development:
  <<: *default_settings
  app_name: 'My Ruby Application (Development)'
  monitor_mode: false
  log_level: 'debug'
  developer_mode: true
  capture_params: true

test:
  <<: *default_settings
  app_name: 'My Ruby Application (Test)'
  monitor_mode: false

production:
  <<: *default_settings
  app_name: 'My Ruby Application (Production)'
  monitor_mode: true
  log_level: 'warn'
  high_security: true
  capture_params: false

Ruby アプリケーションでの New Relic APM 導入により、Ruby エコシステムの豊富なフレームワークとライブラリを活かした詳細なパフォーマンス監視を実現できます。Rails の規約に従った自動計測と柔軟なカスタマイズオプションにより、アプリケーションの継続的な最適化を効果的に支援します。


関連記事