Python outputs logs to files and deletes expired files

Reference:The python logging module prints logs by date and deletes expired logs

官方:15.7. logging — Logging facility for Python — Python 2.7.18 documentation

One simple log printing:
import logging

logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        filename='/home/URL/client/test_log.log',
                        filemode='a')

The default behavior of the logging module can be changed through specific parameters in the logging.basicConfig() function. Available parameters:

filename: Create a FieldHandler with the specified file name (the concept of handler will be explained in detail later), so that the log will be stored in the specified file.

filemode: file opening mode, this parameter is used when filename is specified. The default value is "a" and can also be specified as "w".
format: Specify the log display format used by the handler.
datefmt: Specifies the date and time format.
level: Set rootlogger; the default log level is set to WARNING (log level CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET)
stream: Create a StreamHandler with the specified stream. You can specify the output to sys.stderr, sys.stdout or a file. The default is sys.stderr. If both filename and stream parameters are listed, the stream parameter will be ignored.

Format strings that may be used in the format parameter:
%(name)s Logger’s name
%(levelno)s in numeric form Log level
%(levelname)s Log level in text form
%(pathname)s The full path name of the module that calls the log output function, there may be no a> %(message)s user output message %(process)d process ID. There may not be %(threadName)s thread name. There may be no %(thread)d thread ID. May not %(asctime)s The current time as a string. The default format is "2003-07-08 16:49:45,896". What follows the comma is milliseconds %(relativeCreated)d The number of milliseconds since the Logger was created when outputting log information %(created) f The current time, expressed as a UNIX standard floating-point number representing time %(lineno)d The line of code where the statement that calls the log output function is located %(funcName)s The function name that calls the log output function %(module)s The name of the module that calls the log output function
%(filename)s The file name of the module that calls the log output function









Second, only output to the file and not print in ternimal.

import logging
from logging.handlers import TimedRotatingFileHandler
from logging.handlers import RotatingFileHandler

def log_init():
    log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s'
    formatter = logging.Formatter(log_fmt)
    log_file_handler = TimedRotatingFileHandler(filename=LOG_PATH+"thread_", when="D", interval=1, backupCount=7)
    log_file_handler.suffix = "%Y-%m-%d_%H-%M.log"
    log_file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$")
    log_file_handler.setFormatter(formatter)
    log_file_handler.setLevel(logging.DEBUG)
    log = logging.getLogger()
    log.addHandler(log_file_handler)
   '''
   程序运行
   '''
   #removeHandler 要放在程序运用打印日志的后面
    log.removeHandler(log_file_handler)()

The result is that a log file is generated every day, and the log files for the last 7 days are retained.

when: is a string used to describe the basic unit of the rolling period. The value and meaning of the string are as follows:
“S”: Seconds
“M”: Minutes
“H”: Hours
“D”: Days
“W”: Week day (0=Monday)
“midnight”: Roll over at midnight
interval: rolling period, the unit is specified by when, for example: when='D',interval =1, indicating that one log file is generated every day;
backupCount: indicating the number of retained log files;

Delete log file settings:
log_file_handler.suffix = “%Y-%m-%d_%H-%M.log”
log_file_handler .extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$")< a i=3> The formats of suffix and extMatch should be corresponding, Year-4 digits, m-2 digits and so on


3. Output to file and print to terminal

def initLogging(logFilename):
   
    logging.basicConfig(
                    level    = logging.DEBUG,
                    format   = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s',
                    datefmt  = '%a, %d %b %Y %H:%M:%S',
                    filename = logFilename,
                    filemode = 'w');
  
    console = logging.StreamHandler();
    console.setLevel(logging.INFO);
    formatter = logging.Formatter('LINE %(lineno)-4d : %(levelname)-8s %(message)s');
    console.setFormatter(formatter);
    logging.getLogger('').addHandler(console);

Print to terminal through logging.StreamHandler() function

Guess you like

Origin blog.csdn.net/March_A/article/details/134640811
Recommended