LoginSignup
7
7

More than 5 years have passed since last update.

[Ruby] caller を利用してメソッド呼び出しをログに記録させる。

Last updated at Posted at 2013-12-28

ruby でメソッドの呼び出し状況をログ出力するのにこんな方法は如何?

Util::Trace という module を定義し、
メソッド定義の先頭に Util::Trace.trace() を追加するだけ。

1.rb
# -*- coding: utf-8 -*-
require 'logger'

module Util
  class Trace
    @@enable = true
    @@log = nil

    def self.log=(log)
      @@log = log
    end

    def self.enable=(bool)
      @@enable = bool
    end

    def self.trace(*arg)
      @@log.debug "#{caller.first} (#{arg.join(',')})" if @@enable && @@log
    end
  end
end

def sub
  Util::Trace.trace
end

def sub2(x, y)
  Util::Trace.trace(x, y)
end

log = Logger.new(STDOUT)
log.level = Logger::DEBUG
Util::Trace.log = log

sub
sub2('a', 'b')
sub2('x', a: 1, b: 10)

Util::Trace.enable = false
puts '----- trace off'
# 以下のメソッド呼び出しは TRACE 情報が表示されなくなる。
sub
sub2('c', 'd')
sub2('y', a: 2, b: 20)

Util::Trace.enable = true
puts '----- trace on'
# 以下のメソッド呼び出しは TRACE 情報が表示されるようになる。
sub
sub2('e', 'f')
sub2('z', a: 3, b: 30)

実行させると

$ ruby 1.rb
D, [2013-12-29T09:04:46.005960 #59602] DEBUG -- : 1.rb:24:in `sub' ()
D, [2013-12-29T09:04:46.006628 #59602] DEBUG -- : 1.rb:28:in `sub2' (a,b)
D, [2013-12-29T09:04:46.006753 #59602] DEBUG -- : 1.rb:28:in `sub2' (x,{:a=>1, :b=>10})
----- trace off
----- trace on
D, [2013-12-29T09:04:46.007036 #59602] DEBUG -- : 1.rb:24:in `sub' ()
D, [2013-12-29T09:04:46.007190 #59602] DEBUG -- : 1.rb:28:in `sub2' (e,f)
D, [2013-12-29T09:04:46.007287 #59602] DEBUG -- : 1.rb:28:in `sub2' (z,{:a=>3, :b=>30})
7
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7