Rotate Log

30分プログラム、その144。Rotate Logをやってみよう。

Apacheとかでよくあるログの形式。ログが一定数を越えると、最初のやつから順番に消えていくアレ。

脳内プログラムによると、3行ぐらいのシェルスクリプトでできる気がしてる。けどまあ、Pythonで。

使い方

$ python rot.py test.log foo
$ python rot.py test.log bar
$ python rot.py test.log baz

$ cat test.log
foo
bar
baz

$ python rot.py test.log xyzzy
bar
baz
xyzzy

ソースコード

#! /usr/bin/python
# -*- mode:python; coding:utf-8 -*-
#
# rot.py -
#
# Copyright(C) 2007 by mzp
# Author: MIZUNO Hiroki <hiroki1124@gmail.com> 
# http://mzp.sakura.ne.jp/
#
# Timestamp: 2007/09/27 18:33:53
#
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Python itself.
#
from os.path import exists
import sys

path = sys.argv[1]
new_line = sys.argv[2]

if exists(path):
    io = file(path)
    lines = io.readlines()[-2:]
    io.close()
else:
    lines = []

lines.append(new_line+"\n")

io = file(path,'w')
map(lambda line: io.write(line),lines)