본문 바로가기
WIKI 기술 지식 베이스

Ruby on Rails 로그 수집 (Log Collection)

원문 보기 위키 갱신

로그를 Datadog로 보내려면 Lograge로 파일에 로그를 남기고 Datadog Agent로 그 파일을 tail 하세요. Ruby로 로깅을 설정할 때는 예약 속성을 염두에 두세요.

Lograge를 사용하면 다음 예시처럼 표준 텍스트 기반 로그 형식을:

Started GET "/" for 127.0.0.1 at 2012-03-10 14:28:14 +0100
Processing by HomeController#index as HTML
  Rendered text template within layouts/application (0.0ms)
  Rendered layouts/_assets.html.erb (2.0ms)
  Rendered layouts/_top.html.erb (2.6ms)
  Rendered layouts/_about.html.erb (0.3ms)
  Rendered layouts/_google_analytics.html.erb (0.4ms)
Completed 200 OK in 79ms (Views: 78.8ms | ActiveRecord: 0.0ms)

더 구조화된 다음 JSON 로그 형식으로 변환할 수 있어요:

{
  "timestamp": "2016-01-12T19:15:19.118829+01:00",
  "level": "INFO",
  "logger": "Rails",
  "method": "GET",
  "path": "/jobs/833552.json",
  "format": "json",
  "controller": "jobs",
  "action": "show",
  "status": 200,
  "duration": 58.33,
  "view": 40.43,
  "db": 15.26
}

출처: 문서

본문

로거 설치 및 설정하기 (Install and configure your logger)

{% tab title="Lograge" %}

  1. 프로젝트에 lograge gem을 추가하세요:
    gem 'lograge'
    
  2. 설정 파일에서 다음을 설정해 Lograge를 구성하세요:
    # Lograge config
    config.lograge.enabled = true
    
    # This specifies to log in JSON format
    config.lograge.formatter = Lograge::Formatters::Json.new
    
    ## Disables log coloration
    config.colorize_logging = false
    
    # Log to a dedicated file
    config.lograge.logger = ActiveSupport::Logger.new(Rails.root.join('log', "#{Rails.env}.log"))
    
    # This is useful if you want to log query parameters
    config.lograge.custom_options = lambda do |event|
        { :ddsource => 'ruby',
          :params => event.payload[:params].reject { |k| %w(controller action).include? k }
        }
    end
    

참고: Lograge는 로그에 컨텍스트 정보도 추가할 수 있어요. 자세한 내용은 Lograge 문서를 참고하세요.

이 설정에 대한 더 심층적인 예시는 Rails 애플리케이션 로그 수집·사용자 지정·관리 방법을 참고하세요.

RocketPants

rocket_pants 컨트롤러용 Lograge를 설정하려면 config/initializers/lograge_rocketpants.rb 파일에서 (위치는 프로젝트에 따라 다를 수 있어요):

# Come from here:
#   https://github.com/Sutto/rocket_pants/issues/111
app = Rails.application
if app.config.lograge.enabled
  ActiveSupport::LogSubscriber.log_subscribers.each do |subscriber|
    case subscriber
      when ActionController::LogSubscriber
        Lograge.unsubscribe(:rocket_pants, subscriber)
    end
  end
  Lograge::RequestLogSubscriber.attach_to :rocket_pants
end

{% /tab %}

{% tab title="Grape" %}

  1. 프로젝트에 grape_logging gem을 추가하세요:

    gem 'grape_logging'
    
  2. Grape에 추가 설정을 더하세요:

    use GrapeLogging::Middleware::RequestLogger,
          instrumentation_key: 'grape',
          include: [ GrapeLogging::Loggers::Response.new,
                    GrapeLogging::Loggers::FilterParameters.new ]
    
  3. config/initializers/instrumentation.rb 파일을 만들고 다음 설정을 추가하세요:

    # Subscribe to grape request and log with a logger dedicated to Grape
    grape_logger = Logging.logger['Grape']
    ActiveSupport::Notifications.subscribe('grape') do |name, starts, ends, notification_id, payload|
        grape_logger.info payload
    end
    

{% /tab %}

Datadog Agent 설정하기 (Configure the Datadog Agent)

로그 수집이 활성화된 후 다음 단계에 따라 사용자 지정 로그 수집을 설정해 로그 파일을 tail 하여 Datadog로 보내세요.

  1. Agent 설정 디렉터리의 conf.d/에 ruby.d/ 폴더를 만드세요.
  2. ruby.d/에 다음 내용으로 conf.yaml 파일을 만드세요:
      logs:
        - type: file
          path: "<RUBY_LOG_FILE_PATH>.log"
          service: <SERVICE_NAME>
          source: ruby
          sourcecategory: sourcecode
          ## Uncomment the following processing rule for multiline logs if they
          ## start by the date with the format yyyy-mm-dd
          #log_processing_rules:
          #  - type: multi_line
          #    name: new_log_start_with_date
          #    pattern: \d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])
    
  3. Agent를 재시작하세요.
  4. Agent의 status 하위 명령을 실행하고 Checks 섹션에서 ruby를 찾아 로그가 Datadog에 성공적으로 제출되는지 확인하세요.

로그가 JSON 형식이면 Datadog가 로그 메시지를 자동으로 파싱하여 로그 속성을 추출해요. Log Explorer를 사용해 로그를 확인하고 문제를 해결하세요.

로그와 트레이스 연결하기 (Connect logs and traces)

이 애플리케이션에 APM이 활성화되어 있다면 APM Ruby 로깅 지침에 따라 trace ID와 span ID를 로그에 자동으로 추가해 애플리케이션 로그와 트레이스 간 연결을 개선할 수 있어요.

모범 사례 (Best practices)

가능하면 로그에 추가 컨텍스트(사용자, 세션, 액션, 메트릭)를 더하세요.

단순한 문자열 메시지를 로깅하는 대신 다음 예시처럼 로그 해시를 사용할 수 있어요:

my_hash = {'user' => '1234', 'button_name'=>'save','message' => 'User 1234 clicked on button saved'};
logger.info(my_hash);

해시는 JSON으로 변환되며 user와 button_name에 대한 분석을 수행할 수 있어요:

{
  "timestamp": "2016-01-12T19:15:18.683575+01:00",
  "level": "INFO",
  "logger": "WelcomeController",
  "message": {
    "user": "1234",
    "button_name": "save",
    "message": "User 1234 clicked on button saved"
  }
}

더 알아보기 (Learn more)