python-logging module configuration

logging log output

import logging
import time
import os
import sys
from datetime import datetime


class Logger:

    def __init__(self, log_file_name='monitor'
                 , log_level=logging.DEBUG
                 , log_dir='./logs/'
                 , only_file=False
                 ):

        if not os.path.exists(log_dir):
            os.makedirs(log_dir)

        log_path = os.path.join(log_dir, log_file_name + '_' + str(datetime.now())[:10] + '.txt')
        formatter = logging.Formatter('[%(asctime)s] - %(levelname)s: %(message)s'
                                      , datefmt='%Y-%m-%d %H:%M:%S')

        self.logger = logging.getLogger(log_file_name)
        self.logger.setLevel(log_level)

        file_handler = logging.FileHandler(log_path, encoding="utf-8")
        file_handler.setLevel(log_level)
        file_handler.setFormatter(formatter)
        self.logger.addHandler(file_handler)

        if not only_file:
            stream_handler = logging.StreamHandler()
            stream_handler.setLevel(log_level)
            stream_handler.setFormatter(formatter)
            self.logger.addHandler(stream_handler)

    def debug(self, message):
        self.logger.debug(message)

    def info(self, message):
        self.logger.info(message)

    def warning(self, message):
        self.logger.warning(message)

    def error(self, message):
        self.logger.error(message)

    def cri(self, message):
        self.logger.critical(message)

ex.

logger = Logger(log_file_name='log'
               , log_level=logging.INFO
                , log_dir=logs_save_dir
                , only_file=True
                )

log output

[2023-05-29 17:07:33] - INFO: start get token from openai......
[2023-05-29 17:07:34] - INFO: get token done
[2023-05-29 17:07:36] - INFO: (test chatgpt) Hello! How can I assist you today?

Note:
1. It is not recommended to configure directly on the logging through logging.addHandler, etc., which will take effect at the entire code level, which is also the root node of the logging module. If other modules use the logging method to output logs, your configuration will overwrite the configuration of other modules, resulting in confusion in the final log output. The official is also the recommended logger = logging.getLogger(log_fname)way to configure. ( official description )
Python official logging instructions

Guess you like

Origin blog.csdn.net/yaogepila/article/details/130761261