我想实现这样的日志功能:
def mylog(str)
puts __FILE__, ":"__LINENO__, ":", str # Here how to get __FILE__ and __LINENO__ is my question.
end
当我打电话时mylog:
mylog 'hello' # say I call this in my.rb line 10
我期望输出:
my.rb:10:hello
请帮助正确实现mylog功能。
我想实现这样的日志功能:
def mylog(str)
puts __FILE__, ":"__LINENO__, ":", str # Here how to get __FILE__ and __LINENO__ is my question.
end
当我打电话时mylog:
mylog 'hello' # say I call this in my.rb line 10
我期望输出:
my.rb:10:hello
请帮助正确实现mylog功能。
使用caller是老式的。而是使用caller_locations.
def mylog(str)
caller_locations(1, 1).first.tap{|loc| puts "#{loc.path}:#{loc.lineno}:#{str}"}
end
你必须使用caller
def mylog(str)
caller_line = caller.first.split(":")[1]
puts "#{__FILE__} : #{caller_line} : #{str}"
end
您可能还想知道从中mylog调用的文件...
def mylog(str)
caller_infos = caller.first.split(":")
puts "#{caller_infos[0]} : #{caller_infos[1]} : #{str}"
end
获取行号的正确变量是__LINE__,因此您的函数的正确实现将是
def mylog(str)
puts "#{__FILE__}:#{__LINE__}:#{str}"
end
编辑使输出与您的匹配