SoFunction
Updated on 2024-11-10

Python logging logging to a file and automatically split the operation code

Logging is an essential component of project development and operation. python provides a built-in logging module to accomplish this; with the help of theTimedRotatingFileHandler You can automatically split the log by date, automatically retain the number of log files, etc. The following is a simple package and test of the log.

import logging
import os
from logging import handlers

class Logger(object):
 # Log level relationship mapping
 level_relations = {
 'debug': ,
 'info': ,
 'warning': ,
 'error': ,
 'critical': 
 }

 def __init__(self,
   filename,
   level='info',
   when='D',
   back_count=3,
   fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
 f_dir, f_name = (filename)
 (f_dir, exist_ok=True) # Create a new log folder in the current directory
  = (filename)
 format_str = (fmt) # Set the log format
 (self.level_relations.get(level)) # Set logging levels
 sh = () # Output to the screen
 (format_str) # Setting the format displayed on the screen
 th = (filename=filename, when=when, backupCount=back_count,
      encoding='utf-8') # Handler that writes to a file at a specified interval to automatically generate the file.
 # InstantiateTimedRotatingFileHandler
 # interval is the time interval, backupCount is the number of backup files, if it exceeds this number, it will be deleted automatically, when is the time unit of the interval, the units are as follows:
 # S seconds
 # M points
 # H hours
 # D day
 # 'W0'-'W6' per week (interval=0 for Monday: W0)
 # midnight Every morning
 (format_str) # Set the format of what is written in the file
 (sh) # Add the object to the logger
 (th)

# Testing
if __name__ == '__main__':
 logger = Logger('./logs/2020/', 'debug', 'S', 5).logger
 ('debug')
 ('info')
 ('Warning')
 ('Report an error')
 ('Serious')

 # Separate logging of error
 err_logger = Logger('./logs/2020/', 'error', 'S', 3).logger
 err_logger.error('error error')

For the convenience of testing, we set the time interval to seconds (automatically naming the split file by seconds), and after running a few more times, the redundant log files will be automatically deleted in accordance with the number of configuration files, retaining the log files as shown in the figure above.

Link to original article:/If there are no special instructions the content of this site is Planet Belt original, without consent is prohibited to reproduce!

summarize

To this point this article on Python logging logging to a file and automatically split the article is introduced to this, more related python logging logging content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!