Getting live alerts when your website is visited with Apache, MQTT, and home-assistant

I have a website or two and sometime wish I could get notifications whenever someone visited them, just for fun. Well I did it, and now I can get beeps in my home whenever anyone visits. It’s kind of cool to hear it go off, though normally it will be annoying, so we need a switch for it.

Inventory: I already have set up an apache2 web server with my webpage on it, an MQTT broker, and a home-assistant based home-automation setup, hooked up to my stereo, lights, and other things. (I’m going to skip the installation of all that for this post.)

We all know you can live monitor your apache log with:

tail -f /var/log/apache2/access.log

Turns out, Apache supports Piped Logs which allow you to send your log data to anything. Let’s pipe the Apache log output to a Python script that can trigger events, while at the same time maintaining the regular old text apache log. In your sites-enabled apache config file, change the log line to this:

The script just has to monitor for regular expressions and publish to the MQTT broker when they’re found. I limited it to off-root html files for now, but will tune accordingly.

Note the main loop with sleeping was adapted from this SO post. You will only get a max of 1 alert per second.

Then you just have some simple configuring to do in home-assistant. Here’s my the relevant config. You just setup a MQTT client and a binary sensor based on the MQTT signal that gets flipped on by the above script. Then you make an automation that detects it flipping on, plays a sound and flips it back off, waiting for the next signal from the script. It’s awesome! You could alternatively make a sensor that measures the hit rate and turns a light redder when you are having more traffic, or anything! The possibilities are endless. With home-assistant you an also set up email alerts, SMS, etc. for other kinds of conditions, so this actually makes a really neat, if not convoluted, log monitoring setup. You can also turn the alert automation on and off with a GUI toggle on the frontend.

You may want another one that calls reset_web_alert if it’s on for 1 minutes in case you reboot home-assistant and the MQTT topic is left in the ON position.

Filed to: Narcissism

Leave a Reply

Your email address will not be published. Required fields are marked *