how can i use timed and size raotating filehandler?
ydf0509 opened this issue · comments
def log_file_namer(logger_name: str) -> str:
# path/name.log.N
print('logger_name:',logger_name)
logger_name, backup_number = logger_name.rsplit(".", maxsplit=1)
# path/name.log
logger_name = logger_name.replace(".log", "")
# curr_date = date.today().strftime("%Y_%m_%d") # noqa: DTZ011
curr_date = time.strftime("%Y_%m_%d_%H_%M_%S") # noqa: DTZ011
return f"{logger_name}_{curr_date}_({backup_number}).log"
def my_program():
import concurrent_log_handler
# Now for the meat of your program...
logger = logging.getLogger("MyExample")
logger.setLevel(logging.DEBUG) # optional to set this level here
handler = concurrent_log_handler.ConcurrentRotatingFileHandler(
"/pythonlogs/logger_name_testc.log", "a", maxBytes=512000, backupCount=6
)
handler.namer = log_file_namer
logger.addHandler(handler)
for idx in range(0, 500):
time.sleep(0.1)
print("Loop %d; logging a message." % idx)
logger.debug("%d > A debug message.", idx)
if idx % 2 == 0:
logger.info("%d > An info message.", idx)
print("Done with example; exiting.")
if __name__ == "__main__":
my_program()
i means that ,
when file size should raotate file, then rotate;
when time should raotate file ,but file size is not large enough,also ratate file.
i have test handler namer function, i found that when time should taote but file size is not enough,it can not rotate file.
i means that every day should has at least one file, ignore file size whether or not reach the maxBytes.
how can i do?
The ConcurrentRotatingFileHandler
class does not support time-based rotation at all. You can have a custom namer but it won't obey the rule of rolling over once per day.
I recently added support in version 0.9.23 for a separate new class ConcurrentTimedRotatingFileHandler
that does support time based rotation.
https://github.com/Preston-Landers/concurrent-log-handler#time-based-rotation-settings
It sounds like you probably want to use ConcurrentTimedRotatingFileHandler
with these settings:
ConcurrentTimedRotatingFileHandler(log_path, when="d", interval=1, backupCount=6, maxBytes=0)
This would roll over the log file once per day, and would not restrict the size of the logfile for each day (maxBytes=0).
handler = concurrent_log_handler.ConcurrentTimedRotatingFileHandler(
filename="/pythonlogs/logger_name_testc.log", mode="a", maxBytes=5, backupCount=6,when='s',
)
# handler.namer = log_file_namer
logger.addHandler(handler)
for idx in range(0, 500):
time.sleep(0.1)
print("Loop %d; logging a message." % idx)
logger.debug("%d > A debug message.", idx)
if idx % 2 == 0:
logger.info("%d > An info message.", idx)
print("Done with example; exiting.")
thanks, ConcurrentTimedRotatingFileHandler is that need,it works good