Warning stack trace

Is it possible to retrieve a warning’s stack trace, similar to errors? The reason I’m asking is that I want to trace the source of the warning, as now it shows the line where it’s being thrown, but not the actual code that triggered it.

For example this warning thrown by the Router is actually caused by a completely different file:

2 Likes

Julia doesn’t store stack traces for warnings. However, warning messages are typically written to the stderr stream, so you can turn such warnings to errors (which do have stack traces) by redirecting stderr to a read-only stream:

julia> redirect_stderr(open(touch(tempname()), "r"))
IOStream(<file ...>)

julia> f() = @warn "Find me"
f (generic function with 1 method)

julia> g() = f()
g (generic function with 1 method)

julia> h() = g()
h (generic function with 1 method)

julia> h()
ERROR: ArgumentError: write failed, IOStream is not writeable
Stacktrace:
  [1] unsafe_write(s::IOStream, p::Ptr{UInt8}, nb::UInt64)
    @ Base ./iostream.jl:373
  [2] unsafe_write
    @ ./io.jl:685 [inlined]
  [3] write(s::IOStream, a::Vector{UInt8})
    @ Base ./io.jl:708
  [4] handle_message(logger::Logging.ConsoleLogger, level::Base.CoreLogging.LogLevel, message::Any, _module::Any, group::Any, id::Any, filepath::Any, line::Any; kwargs::Base.Pairs{Symbol, V, Tuple{Vararg{Symbol, N}}, NamedTuple{names, T}} where {V, N, names, T<:Tuple{Vararg{Any, N}}})
    @ Logging ~/.julia/dev/julia/usr/share/julia/stdlib/v1.10/Logging/src/ConsoleLogger.jl:178
  [5] handle_message(logger::Logging.ConsoleLogger, level::Base.CoreLogging.LogLevel, message::Any, _module::Any, group::Any, id::Any, filepath::Any, line::Any)
    @ Logging ~/.julia/dev/julia/usr/share/julia/stdlib/v1.10/Logging/src/ConsoleLogger.jl:106
  [6] macro expansion
    @ ./logging.jl:330 [inlined]
  [7] f()
    @ Main ./REPL[11]:1
  [8] g
    @ ./REPL[12]:1 [inlined]
  [9] h()
    @ Main ./REPL[13]:1
 [10] top-level scope
    @ REPL[14]:1

Originally posted by @stevengj in Terminate after warning is thrown - global setting - #2 by stevengj

With a bit more work you could create a custom logger that prints the stack-trace without throwing, but this was enough for my use case.