Liferay: Groovy Script to Clean Up Audit Events

Published on Mar 1, 2022

Liferay EE/DXP comes with an Audit functionality, which logs all user actions. This may be very helpful to understand what happened inside your system, e.g., if incidents occur, but it may also generate a large data grave. In my case, it filled more than 3 Gigabyte of logging information into the Audit_AuditEvent table over several years.

Because there was no way to delete old entries via the Control Panel, I wrote a little Groovy script to take care of this task. Fetching all entries I wanted to delete (more than 2 mio. events which were older than thirty days) at once took too much memory, so this script deletes the entries in multiple iterations.

You can change the age of entries to keep and the amount of deletions per iteration by changing the two int variables at the beginning of the script.

import java.time.LocalDate;
import java.time.ZoneId;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;

// Delete all entries older than 30 days
int olderThanDays = 30;
// Handle 1.000 entries per iteration
int entriesPerIteration = 1000;

int auditEventCount = 0;
int auditEventDeleteCount = 0;

while (true) {
	DynamicQuery dynamicQuery = AuditEventLocalServiceUtil
	List<AuditEvent> auditEvents = AuditEventLocalServiceUtil
		.dynamicQuery(dynamicQuery, 0, entriesPerIteration);
	auditEventCount = auditEvents.size();
	if (auditEventCount == 0) {
	for (AuditEvent auditEvent: auditEvents) {
	System.out.println("Deleted " + auditEventDeleteCount 
		+ " audit events.");