Created
March 8, 2016 23:09
-
-
Save 844196/6005d79f9011776b2110 to your computer and use it in GitHub Desktop.
loggerライブラリ使用例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ロガーライブラリをロード | |
require 'logger' | |
module AwesomeGem | |
# ロガーを定義 | |
# ログは標準エラー出力(STDERR)へ出力される | |
@@log ||= Logger.new(STDERR).tap do |log| | |
# ログに記録されるアプリケーション名 | |
log.progname = 'AwesomeGem' | |
# 記録するログレベルのデフォルト値 | |
# 指定したレベル以下のログは記録されない | |
# リファレンスでは定数じゃないといけない様に書いてあるが、シンボルでも指定できる | |
log.level = :debug | |
end | |
# ログレベルを変更するためのセッター | |
def self.log_level=(val) | |
@@log.level = val | |
end | |
# サンプル | |
def self.add(i, j) | |
# ログレベル'debug'に記録 | |
@@log.debug 'method call "add"' | |
@@log.debug "arguments: #{i}, #{j}" | |
result = i + j | |
# ログレベル'info'に記録 | |
@@log.info "result: #{result}" | |
result | |
# 例外発生時 | |
rescue => exception | |
# ログレベル'error'に記録 | |
@@log.error exception.class | |
@@log.error exception.message | |
end | |
end | |
# ログレベル'debug'を明示的に指定 | |
AwesomeGem.log_level = :debug | |
AwesomeGem.add 1, 1 | |
#=> D, [2016-03-08T19:01:34.616064 #30225] DEBUG -- AwesomeGem: method call "add" | |
# D, [2016-03-08T19:01:34.616126 #30225] DEBUG -- AwesomeGem: arguments: 1, 1 | |
# I, [2016-03-08T19:01:34.616146 #30225] INFO -- AwesomeGem: result: 2 | |
AwesomeGem.add 1, :foo | |
#=> D, [2016-03-08T19:01:34.616162 #30225] DEBUG -- AwesomeGem: method call "add" | |
# D, [2016-03-08T19:01:34.616177 #30225] DEBUG -- AwesomeGem: arguments: 1, foo | |
# E, [2016-03-08T19:01:34.616257 #30225] ERROR -- AwesomeGem: TypeError | |
# E, [2016-03-08T19:01:34.616284 #30225] ERROR -- AwesomeGem: :foo can't be coerced into Fixnum | |
# ログレベルを'info'へ変更 | |
AwesomeGem.log_level = :info | |
AwesomeGem.add 1, 1 | |
#=> I, [2016-03-08T19:01:34.616146 #30225] INFO -- AwesomeGem: result: 2 | |
AwesomeGem.add 1, :foo | |
#=> E, [2016-03-08T19:01:34.616257 #30225] ERROR -- AwesomeGem: TypeError | |
# E, [2016-03-08T19:01:34.616284 #30225] ERROR -- AwesomeGem: :foo can't be coerced into Fixnum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment