Count Apache errors by hour with a Python log parser
Apache error logs are a practical source of operational evidence. They show when a web application fails, which modules are complaining, and whether a problem arrives in bursts rather than as a steady stream. A small Python utility can turn that raw text into an hourly summary that is easier to act on. Learn more about Les Secrets Des Pêcheurs De Bar Bretons.
Hourly grouping is especially useful when investigating busy websites, scheduled jobs, backup windows, or sudden traffic spikes. A report showing repeated authentication failures at 2 am tells a different story from a handful of syntax errors scattered across the day.
The approach below uses only Python’s standard library. It reads an Apache error log, extracts timestamps, assigns each line to an error category, and counts the categories for every hour represented in the file.
Australian operators should pay close attention to time zones. A server in Sydney may use Australian Eastern time, while a machine in Perth uses AWST and Brisbane does not switch for daylight saving. If a log is stored in UTC, convert it deliberately before interpreting “business hours” or overnight activity.
Define the log shape and counting rules
A common Apache error entry looks like this:
[Mon Mar 18 14:22:31.123456 2024] [core:error] [pid 4210] [client 203.0.113.8:49211] AH00126: Invalid URI in request
The first bracketed value contains the timestamp, while later fields identify the module, severity, process, client, and message. Other Apache versions and modules may produce slightly different fields, so the parser should depend on the timestamp and full message rather than assuming every line has identical wording.
Before writing code, define categories that are useful for operations. “Timeout”, “authentication”, “client”, “proxy”, and “syntax” are often more helpful than recording every Apache message code separately. A fallback category such as “other” prevents unfamiliar messages from disappearing from the report.
Build a parser with Python
The following script accepts a filename from the command line. It supports timestamps with or without microseconds and ignores lines that do not contain a recognisable Apache date.
import re
import sys
from collections import Counter
from datetime import datetime
TIMESTAMP = re.compile(
r"\[(?P<stamp>[A-Z][a-z]{2} [A-Z][a-z]{2} "
r"\d{1,2} \d{2}:\d{2}:\d{2}(?:\.\d+)? \d{4})\]"
)
def parse_timestamp(line):
match = TIMESTAMP.search(line)
if not match:
return None
value = match.group("stamp")
for pattern in ("%a %b %d %H:%M:%S.%f %Y",
"%a %b %d %H:%M:%S %Y"):
try:
return datetime.strptime(value, pattern)
except ValueError:
pass
return None
def classify(message):
text = message.lower()
if "timeout" in text or "timed out" in text:
return "timeout"
if any(word in text for word in ("auth", "password", "permission", "forbidden")):
return "authentication"
if "proxy" in text or "upstream" in text:
return "proxy"
if any(word in text for word in ("syntax", "invalid", "malformed", "request")):
return "client"
return "other"
def count_errors(path):
counts = Counter()
with open(path, encoding="utf-8", errors="replace") as log:
for line in log:
timestamp = parse_timestamp(line)
if timestamp is None:
continue
error_type = classify(line)
counts[(timestamp.hour, error_type)] += 1
return counts
if __name__ == "__main__":
if len(sys.argv) != 2:
raise SystemExit("Usage: python apache_hours.py /path/to/error.log")
for (hour, error_type), total in sorted(count_errors(sys.argv[1]).items()):
print(f"{hour:02d}:00 {error_type:16} {total}")
The Counter uses a tuple containing the hour and category as its key. This keeps the aggregation compact and makes it easy to sort the final output chronologically. The errors="replace" option also lets the program continue when an old log contains an unexpected byte sequence.
Classify messages into useful error types
Keyword classification is deliberately simple. It works well for a first diagnostic tool, but terms can overlap. For example, an invalid request might be caused by a bot, a broken client, or a misconfigured application. If accurate reporting matters, inspect several real log files and adapt the rules to the Apache modules in use.
Apache records severity levels such as error, warn, and notice, but these are not always the same as operational categories. A warning about a proxy timeout and a warning about an authentication failure need different responses, so categorising by message content often produces a more useful dashboard.
A parser rewards the same careful sorting used in Breton fishing lore, where details such as timing and location help distinguish one catch from another. In log analysis, the equivalent details are the hour, module, message, and source address.
Aggregate by hour and print results
The output may look like this:
00:00 authentication 14
00:00 other 3
01:00 timeout 2
09:00 client 27
09:00 proxy 5
Only hours containing errors are printed. That is convenient for quick inspection, though a graph or CSV export may be better when comparing quiet and busy periods. To include empty hours, loop from zero to 23 and use counts.get((hour, category), 0) for each known category.
Hourly totals can expose patterns hidden in a full log. A cluster of client errors during the morning may match a deployment or an office network problem. Repeated overnight authentication failures could indicate automated scanning, which is particularly relevant for public SSH and web infrastructure.
Test against Australian server conditions
Test the script with a copied log before pointing it at a large production file. Include valid entries, malformed lines, dates with and without microseconds, and messages that contain more than one keyword. A temporary file created with Python’s tempfile module can support repeatable tests without modifying live records.
Time-zone assumptions deserve their own test. A Sydney-hosted service may cross the daylight-saving boundary between AEST and AEDT, while Brisbane remains on the same offset all year. Perth-based teams will often read the same incident in AWST. If logs come from cloud instances, containers, or a centralised service, verify whether timestamps are UTC rather than local time.
For a more explicit conversion, parse timestamps as timezone-aware values and use zoneinfo.ZoneInfo("Australia/Sydney"). Keep the original timestamp in reports as well, because converting a record without documenting the source zone can make later incident reviews confusing.
Extend the utility for daily operations
Large logs should be processed incrementally, as the script already does, rather than loaded into memory. For several rotated files, accept multiple paths or read them in chronological order. Apache’s error.log.1 and compressed archives can be handled separately, with decompression added through Python’s gzip module.
A CSV output mode makes the results suitable for spreadsheets, Grafana, or a small monitoring pipeline. You can also retain the module name, count unique client addresses, or emit an alert when a category exceeds a threshold. Keep those additions separate from timestamp parsing so the program remains easy to maintain.
Practical safeguards for reliable reports
A few operating habits make this kind of utility safer and more useful:
- Confirm the server’s time zone before interpreting hourly peaks.
- Preserve the original log files and analyse copies with restricted permissions.
- Test category rules against current Apache modules and application messages.
- Treat client addresses as sensitive operational data when sharing reports.
- Add a clear warning when malformed or unparsed lines are skipped.
- Compare hourly counts across several days before declaring a trend.
- Rotate or archive generated reports so routine analysis does not fill disk space.
Run the script after a deployment, during an incident, or from a scheduled job that analyses yesterday’s completed log. With a modest amount of Python, an unwieldy Apache error file becomes a concise view of when failures happen and what kind of attention they require.
