Systemd logging to external file
Asked Answered
S

2

5

I have the following Systemd service script to run a Spring boot application-

[Unit]
Description=Upstart for Security
After=network.target network-online.target
Wants=network-online.target

[Service]
User=root
WorkingDirectory=/home/ubuntu/security
ExecStart=/usr/bin/java -classpath java -Dspring.profiles.active=stage -jar /home/ubuntu/security/security-0.0.1-SNAPSHOT.jar > /home/ubuntu/security/security.log 2>&1
SuccessExitStatus=143
Restart=on-failure
RestartSec=120s

[Install]
WantedBy=multi-user.target


I save the script in the following location -

 /etc/systemd/system


I ran the following commands to run the systemd service script -

1. sudo systemctl enable security.service -or- sudo systemctl daemon-reload
2. sudo systemctl status security.service 
3. sudo systemctl start security.service


To check logs, I fire the command -

journalctl -u security.service

and use SHIFT+G to scroll to eof

I am able to check the logs by the above steps, but I want them in an external file in location /home/ubuntu/security , as security.log
How can I achieve it? What change do I make in my systemd script?

Solfatara answered 27/4, 2017 at 8:42 Comment(1)
Possible duplicate of How to redirect output of systemd service to a fileInhesion
V
12

You can use syslog to accomplish this. instruct your systemd service to route stdout/stderr to syslog with an identifier and have syslog handle the writing to file.

[Service]
...
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=<your-svc-identifier>

Now add a config to syslog in /etc/rsyslog.d/

if $programname == '<your-svc-identifier>' then /var/log/<your-svc>.log
if $programname == '<your-svc-identifier>' then stop

Reload syslog

$ sudo systemctl restart rsyslog
Vector answered 18/11, 2017 at 19:28 Comment(0)
D
1

Instead of adding complexity through the fan-in fan-out rsyslog, it’s much neater to just have systemd write to your external file directly.

So, to use your example:

StandardOutput=append:/home/ubuntu/security/security.log
StandardError=append:/home/ubuntu/security/security.log

Note that append: is a feature introduced in systemd 240 (though backported to RHEL8 for instance).

Then, add a corresponding entry under /etc/logrotate.d.

Distillate answered 6/7, 2023 at 4:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.