Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 762
showkey Avatar asked Apr 19 '17 01:04

showkey


People also ask

How do I redirect stderr and stdout to a log file?

Understanding the concept of redirections and file descriptors is very important when working on the command line. To redirect stderr and stdout , use the 2>&1 or &> constructs.

How do I redirect stdout and stderr to the same location?

Discussion. &> or >& is a shortcut that simply sends both STDOUT and STDERR to the same place—exactly what we want to do.

How do I redirect stdout of a running process?

The way we can redirect the output is by closing the current file descriptor and then reopening it, pointing to the new output. We'll do this using the open and dup2 functions. There are two default outputs in Unix systems, stdout and stderr. stdout is associated with file descriptor 1 and stderr to 2.

How would you redirect both stdout and stderr of any command to a file?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator. We have created a file named “sample.


2 Answers

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.

like image 72
Gal Dreiman Avatar answered Oct 05 '22 17:10

Gal Dreiman


Just invoke the redirection as root:

sudo sh -c 'python  sslocal -c /etc/shadowsocks.json  > /var/log/ss.log   2>&1' &
like image 45
William Pursell Avatar answered Oct 05 '22 17:10

William Pursell