Add parameter create_directory

This commit is contained in:
Peter J. Holzer 2023-08-07 12:35:06 +02:00
parent 7c440b6ed3
commit f27be774a8
2 changed files with 13 additions and 3 deletions

View File

@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "switchinglogfilehandlers"
version = "0.0.3"
version = "0.0.4"
authors = [
{ name="Peter J. Holzer", email="hjp@hjp.at" },
]

View File

@ -1,13 +1,16 @@
import logging
import os
import os.path
import threading
import time
class TimeoutSwitchingFileHandler(logging.Handler):
def __init__(self, filename, min_timeout=60, max_timeout=3600):
def __init__(self, filename, min_timeout=60, max_timeout=3600, create_directory=False):
super().__init__()
self.basename = filename
self.min_timeout = min_timeout
self.max_timeout = max_timeout
self.create_directory = create_directory
self.fh = None
self.last_emit = 0
self.first_emit = 0
@ -21,6 +24,9 @@ class TimeoutSwitchingFileHandler(logging.Handler):
if not self.fh:
now_tm = time.localtime(now)
filename = self.basename + time.strftime("%Y-%m-%d-%H-%M-%S", now_tm) + "-%06d" % (now % 1 * 1000000) + ".log"
if self.create_directory:
dirname = os.path.dirname(filename)
os.makedirs(dirname, exist_ok=True)
self.fh = open(filename, "a")
self.first_emit = now
self.fh.write(msg)
@ -42,7 +48,7 @@ class TimeoutSwitchingFileHandler(logging.Handler):
self.release()
class TimedSwitchingFileHandler(logging.Handler):
def __init__(self, filename, when='h', utc=False):
def __init__(self, filename, when='h', utc=False, create_directory=False):
super().__init__()
self.basename = filename
when = when.lower()
@ -59,6 +65,7 @@ class TimedSwitchingFileHandler(logging.Handler):
else:
raise ValueError(f"Unknown value “{when}” for when")
self.utc = utc
self.create_directory = create_directory
self.current_filename = None
self.fh = None
@ -73,6 +80,9 @@ class TimedSwitchingFileHandler(logging.Handler):
if new_filename != self.current_filename:
if self.fh:
self.fh.close()
if self.create_directory:
new_dirname = os.path.dirname(new_filename)
os.makedirs(new_dirname, exist_ok=True)
self.fh = open(new_filename, "a")
self.current_filename = new_filename
self.fh.write(msg)