6

I have created a simple HTTP server of files in the current directory using

python3 -m http.server 8000

This works very well for downloading files in this directory. Logging output is directed to the terminal window -- I assume to either stdout or stderr

I want to log activity through this server by writing log to a specified file.

I have tried

python3 -m http.server 8000 > log.txt 2>&1

But this produces an empty log.txt.

What am I doing wrong? Is there a standard way of doing this or do I have to subclass the http.server class? Something like that?

2
  • 1
    Command python3 -m http.server 8000 2> hello.txt will only write the log to the file once the server exits (e.g. with Ctrl + C). Commented Jul 31, 2020 at 15:50
  • 1
    Ah! Rats! I suppose I'll have to get under the hood a bit. Oh well. Commented Jul 31, 2020 at 15:51

2 Answers 2

8

Had a look into the docs, you can use:

python3 -u -m http.server 8000 2> log.txt

The argument -u will make it so that stdout and stderr are not buffered and will be written in real time.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Also I want to run it as a systemd service for a day or so. For this I added ` [Service] Environment=PYTHONUNBUFFERED=1` to the service file and output goes to the systemd journal and to the service status output.
0

Seems to be working just fine for me. How are you verifying the contents of the log.txt? If you are trying to view the contents of the file while the command is running it will not work. After the command has been KeyboardInterrupted, run

cat log.txt | more

Should be fine.

1 Comment

uuoc, use more log.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.