Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pipe Output to a File When Running as a Systemd Service?

I'm having trouble piping the STDOUT & STDERR to a file when running a program as a systemd service. I've tried adding the following to the .service file:

ExecStart=/apppath/appname > /filepath/filename 2>&1 

But this doesn't work. The output is ending up in /var/log/messages and is viewable using journalctl but I'd like a separate file.

I've also tried setting StdOutput=tty but can't find a way of redirecting this to a file.

Any help would be appreciated.

like image 839
MichaelB76 Avatar asked Oct 06 '15 11:10

MichaelB76


People also ask

How do I create a systemd service file?

Creating systemd unit file. You will need to create a custom service unit file under the '/etc/systemd/system/' directory because this is reserved for custom scripts. Any unit file in '/etc/systemd/system' will override the corresponding file in '/lib/systemd/system'.

How do I get systemd Service logs?

Logs collected by systemd can be viewed by using journalctl. The journal is implemented with the journald daemon and it retrieves messages from the kernel, systemd services, and other sources. These logs are gathered in a central location, which makes it easy to review.


2 Answers

systemd.service(5) says:

ExecStart=

Commands with their arguments that are executed when this service is started.

So, systemd runs your /apppath/appname with args >, /filepath/filename, 2>&1

Try:

ExecStart=/bin/sh -c '/apppath/appname > /filepath/filename 2>&1' 
like image 125
Evgeny Vereshchagin Avatar answered Oct 03 '22 15:10

Evgeny Vereshchagin


Try:

ExecStart=/usr/bin/sh -c "/apppath/appname > /filepath/filename 2>&1" 

ExecStart requires the first argument to be a binary (no exceptions), and doesn't allow pipes or redirection. Therefore, use ExecStart to start a shell within which you can do all the fancy things required.

like image 25
Casey Avatar answered Oct 03 '22 17:10

Casey