I’m running a script that starts a load of other processes to do its work.

I’m running the script like

systemd-cat -t foo thescript

If two of these script runs happens at once, I can’t tell them apart because both will tag with foo and journalctl identifies as foo[123] but 123 seems to be the pid of the process that generated the content. So if 123 is the pid of the thescript process at the start, it changes during the run of that script when a process launched by that script generates output.

I’d like a solution like: the 123 is always the parent script’s pid. Or some other way to add field data in that could then be used to separate out the separate runs.

Anyone got any suggestions?

  • dontbelievethis@sh.itjust.works
    link
    fedilink
    arrow-up
    9
    ·
    1 day ago

    The [123] can change because journald attributes each line to the process that wrote it. Rather than fighting that, tag the whole run with something unique.

    Simplest: unique identifier per run

    systemd-cat -t "foo-$$" thescript
    

    Then journalctl -t foo-<pid> gives you one run. You can match all of them with journalctl -o short | grep 'foo-', but filtering by a fixed field is cleaner (see below).

    Better: run it as a transient unit

    systemd-run --unit="foo-$(date +%s)" --collect --pipe --wait thescript
    

    Every child process lands in the same cgroup, so every line gets the same _SYSTEMD_UNIT and _SYSTEMD_INVOCATION_ID, regardless of which process wrote it. Then:

    journalctl -u 'foo-*'
    journalctl _SYSTEMD_INVOCATION_ID=<id>
    

    Add your own field

    If you want a custom field to filter on, LogExtraFields= attaches it to everything the unit logs:

    systemd-run --unit="foo-$$" -p LogExtraFields=RUN_ID=$$ --collect --pipe --wait thescript
    
    journalctl RUN_ID=12345
    

    Add --user if you’re not root and want a user-level unit. systemd-cat itself can’t add extra fields, but systemd-run does everything it does here and more.

    Does that make sense?

    • nettie@lemmy.worldOP
      link
      fedilink
      English
      arrow-up
      1
      ·
      22 hours ago

      True, I could just redirect it all to a file with unique name, then wrote a cron to clean those up over time, instead of using systemd journal.