I am updating a suite of programs for RHEL7, some , some . If they're started as systemd services I would like them to write to the systemd journal. If they're run directly at the terminal, say for testing, I want them to write to stdout instead. How can I do this most elegantly?

I want to take advantage of the journal's advanced features -- logging severity, file name, line number, thread name, etc. -- so simply writing to stdout doesn't suffice.

The searching I've done yielded advice to check the process's parent PID, or check its cgroup. Is there a better way? Those seem like kludgy solutions. Ideally there'd be a function I could call, or an environment variable to check.

Additional info:

(My fallback plan is to use a command-line switch, but it'd sure be nice to autodetect.)

  • How about isatty(3) to see if a terminal is attached? (though I'd probably go with a -d debug flag, as something has to manually signal that, so less surprises if a terminal is somehow detected when it shouldn't) – thrig Sep 30 '16 at 19:37
  • 1
    @thrig Using isatty wouldn't do distinguish between execution by systemd and execution where the output is going to a file (if someone runs johnsprogram >johnsprogram.log then logging on stdout is clearly desired). – Gilles 'SO- stop being evil' Sep 30 '16 at 21:54
  • Your question title doesn't match the body. – JdeBP Oct 1 '16 at 22:40

In systemd version 231 the JOURNAL_STREAM environment variable was introduced for this very purpose. Your program checks its value, compares its value against the device and i-node number of its standard error, and changes its behaviour accordingly.

When not connected to the journal, you could (of course) always employ something like JSON written (as a single line per object) to standard error, to have structured log records there too. RFC 5424 also has (more limited) structured data options.

| improve this answer | |

systemd already handles this case elegantly for you, as documented in systemd.exec.

Log to STDOUT. When run via systemd, systemd will default to redirecting STDOUT to the journal.

Another option is journal+console if you always want to log to both.

Logging to STDOUT is also a best practice in the 12 Factor App design.

| improve this answer | |
  • I should have mentioned that I want to take advantage of the journal's advanced features -- logging severity, file name, line number, thread name, etc. – John Kugelman Sep 30 '16 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.