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?

Stephen Boston
  • 971
  • 1
  • 12
  • 23

2 Answers2

7

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.

Telmo Trooper
  • 4,993
  • 1
  • 30
  • 35
  • 1
    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. – Stephen Boston Jul 31 '20 at 22:56
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.