3

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.)

3
  • 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, 2016 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). Sep 30, 2016 at 21:54
  • Your question title doesn't match the body.
    – JdeBP
    Oct 1, 2016 at 22:40

2 Answers 2

4

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.

4

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.

1
  • 1
    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. Sep 30, 2016 at 21:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .