Thursday, April 27, 2017

How to redirect stderr and stdout into /var/log directory in background process?

Leave a Comment

With the below command ,all stderr and stdout redirect into /tmp/ss.log and it perform in background process.

python  sslocal -c /etc/shadowsocks.json  > /tmp/ss.log   2>&1 & 

Now to redirect stderr and stdout into /var/log directory as following.

python  sslocal -c /etc/shadowsocks.json  > /var/log/ss.log   2>&1 & bash: /var/log/ss.log: Permission denied   

It encounter permission problem.
I made a try with sudo tee as following.

python  sslocal -c /etc/shadowsocks.json  |sudo tee -a /var/log/ss.log   2>&1 & python  sslocal -c /etc/shadowsocks.json  2>&1|sudo tee -a /var/log/ss.log  & nohup python  sslocal -c /etc/shadowsocks.json  |sudo tee -a /var/log/ss.log   2>&1 & nohup python  sslocal -c /etc/shadowsocks.json  2>&1|sudo tee -a /var/log/ss.log  &     

All of them encounter another problem,the command can't run in background process,it run as foreground process.

How to redirect stderr and stdout into /var/log directory in background process?

3 Answers

Answers 1

Just invoke the redirection as root:

sudo sh -c 'python  sslocal -c /etc/shadowsocks.json  > /var/log/ss.log   2>&1' & 

Answers 2

Although you try to redirect stdout / stderr using bash redirection, I may add another alternative: Redirect within your code:

import sys sys.stdout = open(stdout.log, 'w') sys.stderr = open(stderr.log, 'w') 

You just need to execute this code during application startup and all the output (stdout, and stderr) will be written to the defined log files.

Answers 3

sudo vi /etc/systemd/system/ss.service  [Unit] Description=ss  [Service] TimeoutStartSec=0 ExecStart=/bin/bash -c '/python sslocal -c /etc/ss.json 2>&1 > /var/log/ss.log 2>&1'  [Install] WantedBy=multi-user.target 

To start it after editing the config file.

sudo systemctl daemon-reload sudo systemctl enable ss.service sudo systemctl start ss.service sudo systemctl status ss -l 

1.ss run as a service and it start in reboot automatically.
2.ss can write log into /var/log/ss.log without permission problem.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment