OK, the first problem to solve is to give an order or index no to each users' log entries.
Assuming that each entry has an autoinc logid we can number the sequence thus
SELECT t1.userid, COUNT(t1.logid) AS c, t1.logid, t1.logid > = t2.logid AS flg
FROM log t1 INNER JOIN log t2 ON t1.userid = t2.userid
GROUP BY t1.userid, t1.logid, flg
HAVING flg = TRUE
This will return results with each user's log entry numbered in sequence; save it as logview1
Next we need the max sequence no for each user
SELECT userid, MAX(c) AS m FROM logview1
GROUP BY userid
// this expands to
SELECT userid, MAX(c) AS m FROM
(SELECT t1.userid, COUNT(t1.logid) AS c, t1.logid, t1.logid > = t2.logid AS flg
FROM log t1 INNER JOIN log t2 ON t1.userid = t2.userid
GROUP BY t1.userid, t1.logid, flg
HAVING flg = TRUE)
GROUP BY userid
Save this as logview2
Now we can use the 2 queries to get the last 5 logid's for each user
SELECT q1.userid, q1.logid
FROM logview1 q1 INNER JOIN logview2 q2 ON q1.userid = q2.userid
WHERE (q2.m - q1.c) < 5
// this expands as
SELECT q1.userid, q1.logid
FROM
(SELECT t1.userid, COUNT(t1.logid) AS c, t1.logid, t1.logid > = t2.logid AS flg
FROM log t1 INNER JOIN log t2 ON t1.userid = t2.userid
GROUP BY t1.userid, t1.logid, flg
HAVING flg = TRUE) AS q1
INNER JOIN
(SELECT userid, MAX(c) AS m FROM
(SELECT t1.userid, COUNT(t1.logid) AS c, t1.logid, t1.logid > = t2.logid AS flg
FROM log t1 INNER JOIN log t2 ON t1.userid = t2.userid
GROUP BY t1.userid, t1.logid, flg
HAVING flg = TRUE)
GROUP BY userid) AS q2
ON q1.userid = q2.userid
WHERE (q2.m - q1.c) < 5
Might be some syntax errors in there but basically that's it. Save as logview3
Now we can finally do the delete
DELETE FROM log
WHERE logid NOT IN (SELECT logid FROM logview3)