176 lines
6.8 KiB
Python
Executable File
176 lines
6.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""logrotate - tiny log rotator: compress old logs, keep N generations.
|
|
Usage: logrotate DIR [--pattern GLOB] [--keep N] [--max-size SIZE] [--force] [--dry-run] [--selftest]
|
|
Rotates logs over --max-size (default 1M) or all logs with --force: app.log
|
|
becomes app.log.1.gz, older generations shift up, generations past --keep
|
|
are deleted, and the live log is truncated (not deleted) so the writer keeps
|
|
its file handle."""
|
|
import argparse, fnmatch, gzip, os, re, shutil, sys
|
|
|
|
def human(n):
|
|
for u in ("B", "K", "M", "G", "T"):
|
|
if abs(n) < 1024 or u == "T":
|
|
return f"{n:.1f}{u}" if u != "B" else f"{int(n)}B"
|
|
n /= 1024.0
|
|
return f"{n:.1f}T"
|
|
|
|
def parse_size(s):
|
|
m = {"K": 1024, "M": 1024**2, "G": 1024**3}
|
|
if s and s[-1].upper() in m:
|
|
return int(float(s[:-1]) * m[s[-1].upper()])
|
|
return int(s)
|
|
|
|
GEN_RE = re.compile(r"^(.*)\.(\d+)(\.gz)?$")
|
|
|
|
def generations(path):
|
|
"""Existing rotated files for a base log path: {gen_number: full_path}."""
|
|
d = os.path.dirname(path) or "."
|
|
base = os.path.basename(path)
|
|
out = {}
|
|
try:
|
|
names = os.listdir(d)
|
|
except OSError:
|
|
return out
|
|
for name in names:
|
|
m = GEN_RE.match(name)
|
|
if m and m.group(1) == base:
|
|
out[int(m.group(2))] = os.path.join(d, name)
|
|
return out
|
|
|
|
def rotate_one(path, keep, dry_run):
|
|
"""Rotate one log. Returns (actions, bytes_freed_estimate)."""
|
|
actions = []
|
|
gens = generations(path)
|
|
# delete generations at/over keep, shift the rest up
|
|
for g in sorted(gens, reverse=True):
|
|
if g >= keep:
|
|
actions.append(("delete", gens[g]))
|
|
if not dry_run:
|
|
try:
|
|
os.unlink(gens[g])
|
|
except OSError:
|
|
pass
|
|
else:
|
|
dest = f"{path}.{g + 1}.gz"
|
|
actions.append(("shift", gens[g], dest))
|
|
if not dry_run:
|
|
try:
|
|
if gens[g].endswith(".gz"):
|
|
os.rename(gens[g], dest)
|
|
else:
|
|
with open(gens[g], "rb") as f_in, gzip.open(dest, "wb") as f_out:
|
|
shutil.copyfileobj(f_in, f_out)
|
|
os.unlink(gens[g])
|
|
except OSError:
|
|
pass
|
|
# compress the live log into .1.gz and truncate it
|
|
size = 0
|
|
try:
|
|
size = os.path.getsize(path)
|
|
except OSError:
|
|
return actions, 0
|
|
dest = f"{path}.1.gz"
|
|
actions.append(("rotate", path, dest))
|
|
if not dry_run and size > 0:
|
|
try:
|
|
with open(path, "rb") as f_in, gzip.open(dest, "wb") as f_out:
|
|
shutil.copyfileobj(f_in, f_out)
|
|
with open(path, "wb"):
|
|
pass # truncate, keep the inode for the writer
|
|
except OSError:
|
|
pass
|
|
return actions, size
|
|
|
|
def rotate_dir(d, pattern, keep, max_size, force, dry_run):
|
|
results = []
|
|
try:
|
|
names = sorted(os.listdir(d))
|
|
except OSError as e:
|
|
print(f"error: cannot list {d}: {e}", file=sys.stderr)
|
|
return results
|
|
for name in names:
|
|
if not fnmatch.fnmatch(name, pattern):
|
|
continue
|
|
if GEN_RE.match(name):
|
|
continue # already a rotated generation
|
|
path = os.path.join(d, name)
|
|
if not os.path.isfile(path):
|
|
continue
|
|
try:
|
|
size = os.path.getsize(path)
|
|
except OSError:
|
|
continue
|
|
if not force and size < max_size:
|
|
continue
|
|
actions, _sz = rotate_one(path, keep, dry_run)
|
|
results.append((path, size, actions))
|
|
return results
|
|
|
|
def selftest():
|
|
import tempfile
|
|
tmp = tempfile.mkdtemp(prefix="logrotate-test-")
|
|
with open(os.path.join(tmp, "app.log"), "w") as f:
|
|
f.write("line\n" * 100)
|
|
with open(os.path.join(tmp, "app.log.1"), "w") as f:
|
|
f.write("old\n" * 10)
|
|
with open(os.path.join(tmp, "other.log"), "w") as f:
|
|
f.write("tiny")
|
|
# dry run must not change anything
|
|
res = rotate_dir(tmp, "*.log", keep=2, max_size=100, force=False, dry_run=True)
|
|
ok = True
|
|
if os.path.getsize(os.path.join(tmp, "app.log")) == 0:
|
|
print("FAIL: dry run truncated the log"); ok = False
|
|
if not any(r[0].endswith("app.log") for r in res):
|
|
print("FAIL: dry run did not select app.log"); ok = False
|
|
if any(r[0].endswith("other.log") for r in res):
|
|
print("FAIL: tiny log selected without --force"); ok = False
|
|
# real run: app.log -> .1.gz, old .1 -> .2.gz, live log truncated
|
|
rotate_dir(tmp, "*.log", keep=2, max_size=1, force=True, dry_run=False)
|
|
if not os.path.exists(os.path.join(tmp, "app.log.1.gz")):
|
|
print("FAIL: app.log.1.gz missing"); ok = False
|
|
if not os.path.exists(os.path.join(tmp, "app.log.2.gz")):
|
|
print("FAIL: app.log.2.gz missing (old .1 not shifted)"); ok = False
|
|
if os.path.getsize(os.path.join(tmp, "app.log")) != 0:
|
|
print("FAIL: live log not truncated"); ok = False
|
|
with gzip.open(os.path.join(tmp, "app.log.1.gz"), "rt") as f:
|
|
if f.read().count("line") != 100:
|
|
print("FAIL: rotated content wrong"); ok = False
|
|
shutil.rmtree(tmp, ignore_errors=True)
|
|
if ok:
|
|
print("selftest: PASS (dry-run safe, rotate+shift+truncate+keep=2 all correct)")
|
|
return 0 if ok else 1
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(prog="logrotate",
|
|
description="Tiny log rotator: compress old logs, keep N generations.")
|
|
ap.add_argument("dir", nargs="?", help="directory holding the logs")
|
|
ap.add_argument("--pattern", default="*.log", help="log filename glob (default *.log)")
|
|
ap.add_argument("--keep", type=int, default=5, help="generations to keep (default 5)")
|
|
ap.add_argument("--max-size", default="1M", help="rotate logs at least this big (default 1M)")
|
|
ap.add_argument("--force", action="store_true", help="rotate every matching log regardless of size")
|
|
ap.add_argument("--dry-run", action="store_true", help="show what would happen, change nothing")
|
|
ap.add_argument("--selftest", action="store_true", help="run built-in checks in a temp dir")
|
|
a = ap.parse_args()
|
|
if a.selftest:
|
|
return selftest()
|
|
if not a.dir:
|
|
ap.error("dir is required")
|
|
res = rotate_dir(a.dir, a.pattern, a.keep, parse_size(a.max_size), a.force, a.dry_run)
|
|
if not res:
|
|
print("nothing to rotate.")
|
|
return 0
|
|
for path, size, actions in res:
|
|
print(f"{path} ({human(size)}):")
|
|
for act in actions:
|
|
if act[0] == "delete":
|
|
print(f" delete {act[1]}")
|
|
elif act[0] == "shift":
|
|
print(f" {act[1]} -> {act[2]}")
|
|
else:
|
|
print(f" {act[1]} -> {act[2]} (live log truncated)")
|
|
print(f"{'would rotate' if a.dry_run else 'rotated'} {len(res)} log(s).")
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|