I am updating a suite of programs for RHEL7, some c++, some java. 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:
- For the c++ programs I plan to call sd_journal_print(3).
- For the java programs I plan to use SLF4J + Logback + logback-journal.
(My fallback plan is to use a command-line switch, but it'd sure be nice to autodetect.)
isatty(3)to see if a terminal is attached? (though I'd probably go with a-ddebug flag, as something has to manually signal that, so less surprises if a terminal is somehow detected when it shouldn't)isattywouldn't do distinguish between execution by systemd and execution where the output is going to a file (if someone runsjohnsprogram >johnsprogram.logthen logging on stdout is clearly desired).