systemd: how to redirect stdout to logfile

30,846

Solution 1

Use:

[Unit]
Description=My application
[Service]
ExecStart=/usr/bin/java -jar myapp.jar
Type=simple
User=photo
StandardOutput=file:/var/log/logfile

as documented here: https://www.freedesktop.org/software/systemd/man/systemd.exec.html#StandardOutput=

Note that this way log files contents will be overwritten each time service restarts. StandardOutput/Error systemd directives do not support appending to files.

If you want to maintain file log between service restarts and just append new logged lines to it, use instead:

[Unit]
Description=My application
[Service]
ExecStart=/usr/bin/sh -c 'exec /usr/bin/java -jar myapp.jar'
Type=simple
User=photo

exec means that shell program will be substituted with /bin/java program after setting up redirections without forking. So there will be no difference from running /bin/java directly after ExecStart=.

Solution 2

If your app is a Python script you also need to set

Environment=PYTHONUNBUFFERED=1

Otherwise you will not see any log messages until the buffer is flushed.

Share:
30,846

Related videos on Youtube

exeral
Author by

exeral

Updated on September 18, 2022

Comments

  • exeral
    exeral 3 months

    I have a systemd service:

    [Unit]
    Description=My application
    [Service]
    ExecStart=/bin/java myapp.jar
    Type=simple
    User=photo
    

    There is an option: StandardOutput= but I don't understand how to use it to write to a file. https://www.freedesktop.org/software/systemd/man/systemd.exec.html

    I was expecting to put a filepath somehere but the documentation talks about sockets and file descriptors. seems it needs more configuration than just that keyword.

    Where to put the filepath ? I can't find any examples of that use

    Thanks

  • Ryan Burnette
    Ryan Burnette almost 4 years
    what about append: instead of file:?
  • Hindol
    Hindol about 3 years
    It is worth mentioning append: is available only in systemd 240+.
  • a-h
    a-h almost 2 years
    Also file: is only available in 236+. You can find the version with systemctl --version. At time of writing Amazon Linux 2 ships with 219...
  • Brad Grissom
    Brad Grissom over 1 year
    I realize this doesn't answer the original question, but as somebody searching for why my (python-based) service isn't logging stdout, this solves my problem.