Skip to content
← Back to Snippets
Code

Log Rotation Threshold Plan

Builds a rotation plan for application logs based on byte size, age, and retention limits.

Purpose

Builds a rotation plan for application logs based on byte size, age, and retention limits.

Snippet details

ContextFileLevelAdvancedCopy-and-paste statusMarked safe after review.

Categories

  • Security

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Log Rotation Threshold Plan.
 *
 * Purpose:
 * Builds a rotation plan for application logs based on byte size, age, and retention limits.
 *
 * @param array $log_rows Log rows with path, bytes, and modified_at.
 * @param int $max_bytes Maximum active log size.
 * @param int $retention_days Retention window for rotated logs.
 * @return array Log rotation plan.
 */
function ogSnippetLogRotationThresholdPlan(array $log_rows, int $max_bytes, int $retention_days): array {
	$now = time();
	$plan = array();
	foreach ($log_rows as $log_row) {
		$bytes = (int) $log_row['bytes'];
		$age_days = (int) floor(($now - (int) $log_row['modified_at']) / 86400);
		$action = 'keep';
		if ($bytes > $max_bytes) {
			$action = 'rotate';
		}
		if ($age_days > $retention_days) {
			$action = 'archive_or_delete';
		}
		$plan[] = array('path' => (string) $log_row['path'], 'age_days' => $age_days, 'bytes' => $bytes, 'action' => $action);
	}
	return $plan;
}

$log_rows = array(array('path' => '/logs/tycho-station.log', 'bytes' => 8100000, 'modified_at' => time() - 86400));
$rotation_plan = ogSnippetLogRotationThresholdPlan($log_rows, 5000000, 30);
echo $rotation_plan[0]['action'];