This set of files is to help you set up a socket listener for Python logging in a production environment.
The other files are:
Filename | Purpose |
---|---|
prepare.sh | A Bash script to prepare the environment for testing. |
supervisor.conf | The Supervisor configuration file, which has entries for the listener and a multi-process web application. |
ensure_app.sh | A Bash script to ensure that Supervisor is running with the above configuration. |
log_listener.py | The socket listener program which receives log events and records them to a file. |
main.py | A simple web application which performs logging via a socket connected to the listener. |
webapp.json | A JSON configuration file for the web application. |
client.py | A Python script to exercise the web application. |
The web application uses Gunicorn, which is a popular web application server that starts multiple worker processes to handle requests. This example setup shows how the workers can write to the same log file without conflicting with one another — they all go through the socket listener.
To test these files, do the following in a POSIX environment:
-
Download the Gist as a ZIP archive using the Download ZIP button.
-
Unzip the above files from the archive into a scratch directory.
-
In the scratch directory, run
bash prepare.sh
to get things ready. This creates arun
subdirectory to contain Supervisor-related and log files, and avenv
subdirectory to contain a virtual environment into whichbottle
,gunicorn
andsupervisor
are installed. -
Run
bash ensure_app.sh
to ensure that Supervisor is running with the above configuration. -
Run
venv/bin/python client.py
to exercise the web application, which will lead to records being written to the log. -
Inspect the log files in the
run
subdirectory. You should see the most recent log lines in files matching the patternapp.log*
. They won’t be in any particular order, since they have been handled concurrently by different worker processes in a non-deterministic way.
You can shut down the listener and the web application by running venv/bin/supervisorctl -c supervisor.conf shutdown
.
The default configuration uses a TCP socket on port 9020. You can use a Unix Domain socket instead of a TCP socket by doing the following:
- In
listener.json
, add asocket
key with the path to the domain socket you want to use. If this key is present, the listener listens on the corresponding domain socket and not on a TCP socket (theport
key is ignored). - In
webapp.json
, change the socket handler configuration dictionary so that thehost
value is the path to the domain socket, and set theport
value tonull
.