How to Get the Last Requests to Apache2 Server?


The apache server logs the access requests in /var/log/apache2 so we can analyse this log file to find out the last few requests.

The following parses the apache2 server logs, and print the requests line by line. It is based on the BASH commands: awk and tail.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash 
 
NUMBER_OF_REQUESTS=50
LOG_FILES_PREFIX=/var/log/apache2/access
 
tail -n $NUMBER_OF_REQUESTS $LOG_FILES_PREFIX* | awk -F'"' '
    # Ensure the IP address, request, and user agent fields are present
    $1 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/ && $2 ~ /^(GET|POST|HEAD|PUT|DELETE|OPTIONS|PATCH)/ && $6 != "" {
        split($1, part1, " ")
        ip = part1[1]
        split($2, request, " ")
        method = request[1]
        path = request[2]
        user_agent = $6
        print ip, path, user_agent
    }
'
#!/bin/bash 

NUMBER_OF_REQUESTS=50
LOG_FILES_PREFIX=/var/log/apache2/access

tail -n $NUMBER_OF_REQUESTS $LOG_FILES_PREFIX* | awk -F'"' '
    # Ensure the IP address, request, and user agent fields are present
    $1 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/ && $2 ~ /^(GET|POST|HEAD|PUT|DELETE|OPTIONS|PATCH)/ && $6 != "" {
        split($1, part1, " ")
        ip = part1[1]
        split($2, request, " ")
        method = request[1]
        path = request[2]
        user_agent = $6
        print ip, path, user_agent
    }
'

Example output (each line containing the IP Address, URI/URL, and User Agent):

last-few-access-apache2-logs How to Get the Last Requests to Apache2 Server? awk AWK AWK programming BASH bash script DevOps

Last Few Requests to Apache2 by IP, URL and User Agent

With this, we can integrate to the BASH script that sends an email notification when CPU load average is high, to help us understand what cause(s) the spike.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
290 words
Last Post: Two Windows Tips: Turn Off Delivery Optimization and Tweak Privacy Settings
Next Post: Teaching Kids Programming - SQL to Determine the Binary Tree Node Types (Left/Right Join - Process Elimination)

The Permanent URL is: How to Get the Last Requests to Apache2 Server?

Leave a Reply