简体   繁体   中英

Python3 http.server : save log to a file

I use Python3.6 to write a simple HTTP server to redirect all requests.

The file I written can be found here

I can see output in both Win8.1 CMD & Ubuntu 16.04.3 Bash. However , whatever I try any of those methods below , it doesn't work , the log cannot be saved into the file.

nohup python3 ./filename.py > ./logfile 2>&1 &
python3 ./filename.py > ./logfile 2>&1 &
setsid ./filename.py > ./logfile 2>&1 &

I tried to use:

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

It didn't work.

i've tried your code on Ubuntu 16.04 and it worked like charm.

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

By default, Python's stdout and stderr are buffered. As other responders have noted, if your log files are empty then (assuming your logging is correct) the output has not been flushed.

The link to the script is no longer valid, but you can try running your script either as python3 -u filename.py or the equivalent PYTHONUNBUFFERED=x python3 filename.py . This causes the stdout and stderr streams to be unbuffered.

A full example that uses the standard library's http.server module to serve files from the current directory:

PYTHONUNBUFFERED=x python3 -m http.server &> http.server.log & echo $! > http.server.pid

All output (stdout & stderr) is redirected to http.server.log , which can be tailed, and the process ID of the server is written to http.server.pid so that you can kill the process by kill $(cat http.server.pid) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM