02 Python 基礎教學10 所有文章

【學習筆記】 Python 如何寫logging教學+yaml配置

logging

首先建立一份文件檔命名為config.yaml,所有logger的設定都會在這份文檔裡面,統一在這份文件檔方便於之後不用各別修改py檔內的設定!可以先複製這份,接下來會詳細解說,理解後再修改成自己需要的設置~

version: 1
disable_existing_loggers: no  # 是否覆蓋以前的配置logger
formatters:
        simple:
            format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

root: #默認情況下配置
    level: INFO
    handlers: [console,info_file_handler,error_file_handler]

loggers: #如果有設定loggers的話會採用,否則採用root設定
    my_module1:
            level: INFO
            handlers: [console,info_file_handler]
            propagate: no
    my_module2:
            level: INFO
            handlers: [console,info_file_handler]
            propagate: no

handlers:
    console:
            class: logging.StreamHandler
            level: DEBUG
            formatter: simple
            stream: ext://sys.stdout
    info_file_handler:
            class: logging.handlers.RotatingFileHandler
            level: INFO
            formatter: simple
            filename: /Users/max/Documents/GitHub/document/debug.log
            maxBytes: 5242880
            backupCount: 1
            encoding: utf8
    error_file_handler:
            class: logging.handlers.RotatingFileHandler
            level: ERROR
            formatter: simple
            filename: /Users/max/Documents/GitHub/document/errors.log
            maxBytes: 5242880
            backupCount: 1
            encoding: utf8

再來建立一個python檔,首先看到class log裡面是在讀取config.yaml的配置,def logging1內的return logging.getLogger(‘my_module1’),my_module1這段是對應到config.yaml內的my_module1配置;而def logging2內的return logging.getLogger(‘my_module2’),這段是對應到config.yaml內的my_module2配置;最後 def logging3內的return logging.getLogger()保留為空白在代表會採用root的配置。

import yaml
import logging
import logging.config


class log:
    def __init__(self):
        pass

    def logging1(self,default_path='config.yaml', default_level=logging.INFO):
        path = default_path
        with open(path, 'r', encoding='utf-8') as f:
            config = yaml.load(f)
            logging.config.dictConfig(config)
            return logging.getLogger('my_module1')

    def logging2(self,default_path='config.yaml', default_level=logging.INFO):
        path = default_path
        with open(path, 'r', encoding='utf-8') as f:
            config = yaml.load(f)
            logging.config.dictConfig(config)
            return logging.getLogger('my_module2')

    def logging3(self,default_path='config.yaml', default_level=logging.INFO):
        path = default_path
        with open(path, 'r', encoding='utf-8') as f:
            config = yaml.load(f)
            logging.config.dictConfig(config)
            return logging.getLogger()


class crawler:

    def __init__(self,path):
        # log設定
        yaml_path = path
        self.setup = log()
        self.logger1 = self.setup.logging1(default_path=yaml_path)
        self.logger2 = self.setup.logging2(default_path=yaml_path)
        self.logger3 = self.setup.logging3(default_path=yaml_path)
        self.main()

    def main(self):
        self.logger1.info('aaaaa')
        self.logger2.info('aaaaa')
        self.logger3.info('aaaaa')


if __name__=='__main__':

    path ='/Users/max/Documents/GitHub/document/config.yaml'
    crawler(path)

運行後可以看到console出現三行分別是my_module1、my_module2和root的logger的結果。

>>>2019-04-21 12:35:56,792 – my_module1 – INFO – aaaaa

>>>2019-04-21 12:35:56,793 – my_module2 – INFO – aaaaa

>>>2019-04-21 12:35:56,793 – root – INFO – aaaaa

如果想修log的內容的話可以從config.yaml內的format修改

formatters:
simple:
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

%(asctime)s :代表時間

%(name)s:logger的名稱

%(levelname)s:級別

%(message)s :輸入的內容

%(thread)d:線程ID

%(threadName)s:線程ID名稱

除了info外還有CRITICAL > ERROR > WARNING > INFO > DEBUG可以使用,使用方法如下:

logger.info('info')
logger.debug('debug')
logger.warning('warning')
logger.error('error')

關於Python教學的延伸閱讀:

那[學習筆記] Python 如何寫logging教學 就到這邊感謝收看,如文章內容有誤請不吝指正!

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *