lwzm
7/10/2014 - 8:38 AM

file-logger like logging.handlers.TimedRotatingFileHandler

file-logger like logging.handlers.TimedRotatingFileHandler

import os
import pathlib
import time
import sys


def get_logger(logfilename, logsuffix_timefmt="%y%m%d", patch_stderr=False):
    strftime = time.strftime
    timefmt = "%y%m%d%H%M%S"
    assert timefmt.find(logsuffix_timefmt) == 0, logsuffix_timefmt
    logsuffix = strftime(logsuffix_timefmt)
    length = len(logsuffix)
    key = length - 1

    def gen_log_file():
        f = open(logfilename, "a", 1)
        if patch_stderr:
            sys.stderr = f
        return f

    logfile = gen_log_file()

    def rotate_log_file(newsuffix):
        nonlocal logsuffix, logfile
        os.rename(logfilename, "{}.{}".format(logfilename, logsuffix))
        logfile.close()
        logfile = gen_log_file()
        logsuffix = newsuffix

    def log(*args):
        t = strftime(timefmt)
        if t[key] != logsuffix[key]:
            rotate_log_file(t[:length])
        print(t[length:], *args, file=logfile)

    return log
    

class Log:
    def __init__(self, prefix=""):
        self.prefix = prefix
        self._day = None
        self._file = None
        
    def __call__(self, *args):
        print(time.strftime("%H%M%S"), *args, sep="\t", file=self.file, flush=True)
    
    @property
    def file(self):
        day = time.strftime("%d")
        if self._day == day:
            return self._file
        fp = pathlib.Path(self.prefix + day)
        if fp.exists() and time.time() - fp.stat().st_mtime > 86400:
            fp.unlink()
        self._file and self._file.close()
        self._file = fp.open("a")
        self._day = day
        return self._file