Search code examples
elixirelixir-iex

How to get Line Numbers in Console Outputs in Elixir


I need to get line numbers for IO.puts or IO.inspect or any other kind of output that appears on elixir console for the purpose of debugging. Is there an in-built feature for this? Or is there any other easy way to achieve the same?

P.S: By Line Number for IO.puts, I mean the line where IO.puts is written in the code.


Solution

  • You're probably looking for __ENV__, which will give you access to the current file and line (among other things). You could do something like this:

    Logger.debug("#{__ENV__.file}:#{__ENV__.line}: #{inspect some_value}")
    

    Edit: as José suggested in the comments, the better way to do this is to use the metadata feature of logger. At the moment, you can only add the :module, :function and :line keys:

    # config/config.exs
    
    config :logger, :console, metadata: [:module, :function, :line]
    

    However, I made a PR to add the :file key as well. It is already merged and should be released with the next version of Elixir. With the new version you can do

    # config/config.exs
    
    config :logger, :console, metadata: [:file, :line]