Is it possible to suppress a message printed by a function?

Hello,

In R there are two function to print a message in the console: cat and message. The message function is better because it is possible to turn off the message it displays (with the suppressMessages function). This is useful in a Rmarkdown or Quarto document, there’s a chunk option to suppress the messages.

I did a function which prints some messages with printstyled. Is it possible to turn off these messages? Obviously I could add an argument messages = true/false in my function but this is not what I want.

You could make it dependent on a global variable. Probably that’s similar to what happens in the others languages.

Have you looked at this?

Are you looking for something like this:

julia> function output(x)
       printstyled(x;color=1)
       end
output (generic function with 1 method)

julia> output("Hello")
Hello
julia> so = stdout
Base.TTY(Base.Libc.WindowsRawSocket(0x0000000000000274) open, 0 bytes waiting)

julia> redirect_stdout(devnull)
Base.DevNull()

julia> output("Hello")

julia> redirect_stdout(so)
Base.TTY(Base.Libc.WindowsRawSocket(0x0000000000000274) open, 0 bytes waiting)

julia> output("Hello")
Hello
3 Likes

A macro based on @oheil answer:

julia> macro noprint(expr)
           quote
               let so = stdout
                   redirect_stdout(devnull)
                   res = $(esc(expr))
                   redirect_stdout(so)
                   res
               end
           end
       end
@noprint (macro with 1 method)

julia> output(x) = printstyled(x; color=1)
output (generic function with 1 method)

julia> output("Hello")
Hello
julia> @noprint output("Hello")

2 Likes

The analogue of this in Julia is the Logging standard library, which allows lots of control over message visibility and archiving.

For example:

julia> for i = 1:5
          @info "Reached iteration $i"
       end
[ Info: Reached iteration 1
[ Info: Reached iteration 2
[ Info: Reached iteration 3
[ Info: Reached iteration 4
[ Info: Reached iteration 5

julia> global_logger(ConsoleLogger(Warn));

julia> for i = 1:5
          @info "Reached iteration $i"
       end # no output anymore!

julia> 
2 Likes

See also https://julialogging.github.io/ for more documentation and very useful extensions. In particular the LoggingExtras package.

2 Likes

Looks good. Is it possible to print in color with @info?

Based on this:

julia> using Logging, LoggingExtras

julia> log_fmtr = FormatLogger() do io, args
           printstyled(io, "$(args.level): $(args.message)\n"; color=1)
       end
FormatLogger(var"#186#187"(), Base.TTY(Base.Libc.WindowsRawSocket(0x0000000000000270) open, 0 bytes waiting), true)

julia> with_logger(log_fmtr) do; @info "This is in red." end
Info: This is in red.
2 Likes