How to redirect stderr and stdout to / var / log in the background?

advertisements

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?


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.