Search code examples
javaloggingmessagesystemd

Filter System.out.println messages in journalctl by Error, Warn, Info


How can I Filter Messages in Java, that is controlled by Systemd?

At the moment, I'm writing logs using System.out.println like this:

System.out.println("Hello this is a Error");

and the Journalctl -b -u test.service gives me this:

Nov 02 11:58:41 test java[10]: Hello this is a Error

I would like to do something like this

Consider a pseudocode:

System.out.println("Hello this is a Error", "Warn");

and obtain the following:

Nov 02 11:58:41 test java[10] [Error]: Hello this is a Error

But I don't want to use Log4j or any other Library. Maybe I just don't know what to search for, can't find a solution. Hope somebody has an idea.


Solution

  • System.err

    I suspect you want something very simple, so you can try the error output stream accessible via System.err. It can be used pretty match like a standard output stream System.out with which you're already familiar.

    You can create your own message patterns and apply them using printf() (refer to the official tutorial provided by Oracle for more information on string formatting).

    System.err.println("message");
            
    System.err.printf(LocalDate.now() + " : %s", "message");
    

    The message would be printed on the Console, highlighted in red. That's it.

    Java logging API

    If you want something more elaborate, Java has a built-in logging API (no external dependencies required). It resides in the java.util.logging (that's why it's called JUL for short) and offers lots of functionality and many tools including Loggers, Handler, Filters, Formatters, etc. You can learn more about it here.

    Here's a very dummy example:

    Logger logger = Logger.getLogger("myLogger");
    logger.log(Level.WARNING, "something is wrong");
    

    That said, if you would decide to use JUL, you at least need to be aware what are the downsides of it and why other logging tool exist.

    For instance, you can read this question:

    Why not use java.util.logging?