Crystal: [RFC] nameof or similar function used for logging

Created on 24 Sep 2015  路  8Comments  路  Source: crystal-lang/crystal

Is there a way to stringify the current class and method name? I would like the following to be a constant string.

    log {{ "#{__FILE__}:#{__LINENO__} #{self.class.to_s}.#{current_method_name}" }}
draft compiler

Most helpful comment

This will be possible in the next version by doing {{@def.name.stringify}}

All 8 comments

self.class.name works if I only want a single string.
"#{self.class.name}:method_name" returns a new string each time.
"{{ self.class.name }}" fails to compile so I can't create something more complex in a macro.

{{@type.name}} should work though

What about the method name?

I guess we could have a @method macro variable. It always helps if you show why you want this (and it's more than just a single line).

Debugging memory allocations is hard, especially when caller is unavailable. If I had a compile time constant string to log it would help me debug GC and thread related problems.

macro debug msg = nil
  str = {{ "#{@type.name}:#{@method.name} #{msg}" }}
  LibC.write 2, str, str.bytesize
end

For console style debugging this would be really helpful :) (and honestly I do console-debugging in languages with good debuggers too - resorting to the debugger once or twice in a year. Has proven the most efficient way to me.)

This will be possible in the next version by doing {{@def.name.stringify}}

Was this page helpful?
0 / 5 - 0 ratings