[systemd-devel] Detecting when running under systemd
Mantas Mikulėnas
grawity at gmail.com
Wed Aug 17 06:54:59 UTC 2022
On Wed, Aug 17, 2022 at 5:05 AM Peter Hoeg <peter at hoeg.com> wrote:
>
> Hi all,
>
> I have a small program that queries an external web API, massages the data
> and passes it off to something else. As I only need it to run during
> certain windows and I didn't want to have to bother with making sure it was
> alive, I am starting it using a systemd timer which is sufficiently
> flexible. All good and it's super nice to be able to "outsource" all that
> to systemd.
>
> My question is - what is the canonical way to detect that I'm running
> under systemd so that I can adjust accordingly? Currently I'm checking for
> the existence of the "_SYSTEMD_INVOCATION_ID" environment variable in order
> to change the logging function as the default logger includes a timestamp
> which is redundant when journald is picking it up.
>
> I'm also using LoadCredential for passing tokens but that just comes down
> to looking for the right file name where the CREDENTIALS_DIRECTORY variable
> points, so that really isn't systemd specific and there is a fallback in
> case that isn't set or the directory/file doesn't exist anyway.
>
> I could of course also add a --systemd flag that toggles this but if I can
> do "TheRightThing(tm)" out of the box, why not.
>
What *is* specific to systemd that you need to check for and how would that
change the program's behavior? It sounds to me that being started by pid1
is irrelevant here – if you want to alter your logging, then you want to
check specifically whether stderr is tied to the journal, for which you can
use JOURNAL_STREAM (like in
https://github.com/systemd/systemd/blob/main/src/basic/log.c#L217).
(In addition to disabling the timestamps you should *at least* add message
priority indicators as well, either by using SyslogLevelPrefix=, or by
avoiding stderr entirely and using the syslog() API for logging – if not
going all the way with sd_journal_send*().)
--
Mantas Mikulėnas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.freedesktop.org/archives/systemd-devel/attachments/20220817/a2f78221/attachment.htm>
More information about the systemd-devel
mailing list