smarthomeNG / smarthome

Device integration platform for your smart home
https://www.smarthomeNG.de
GNU General Public License v3.0
122 stars 91 forks source link

Log configuration: allow placeholders for filename and rotate correctly #607

Closed onkelandy closed 10 months ago

onkelandy commented 1 year ago

As the core has almost all features implemented that the datalog plugin features I wanted to implement the one feature missing: using placeholders in the filename. I was successful so far with this code, however - when rotating the file it would be necessary to write into a newly created file with the same placeholder but new values instead of the old one. e.g.: filename: ./var/log/test{year}_{hour}.csv

class ShngTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
    """
    TimedRotatingFilehandler with a different naming scheme for rotated files
    """
    def __init__(self, filename, when='MIDNIGHT', interval=0, backupCount=0, encoding=None, delay=False, utc=False):
        self._originalname = os.path.basename(filename)
        super().__init__(self.parseFilename(filename), when, interval, backupCount, encoding, delay, utc)

    def parseFilename(self, filename):
        year = datetime.datetime.now().strftime("%Y")
        month = datetime.datetime.now().strftime("%m")
        day = datetime.datetime.now().strftime("%d")
        hour = datetime.datetime.now().strftime("%H")
        minute = datetime.datetime.now().strftime("%M")
        stamp = datetime.datetime.now().timestamp()

        try:
            return eval(f"f'{filename}'")
        except Exception:
            return filename

    def doRollover(self):
        prs = self.parseFilename(self._originalname)
        if prs != self._originalname:       
            dfn = self.rotation_filename(self.baseFilename)
            sfn = os.path.dirname(self.baseFilename) + "/" + self.parseFilename(self._originalname)
           ... do something useful here.. however, when using self.rotate the log entries get written into the original name, not the new one...
onkelandy commented 10 months ago

Done