1. 程式人生 > 其它 >python模組之logging模組

python模組之logging模組

logging日誌模組

日誌模組的內容很多 但需要掌握的很少(會用即可)  # 個人觀點
import logging


# 日誌有五個等級(從上往下重要程度不一樣)
# logging.debug('debug級別')  # 10
# logging.info('info級別')  # 20
# logging.warning('warning級別')  # 30
# logging.error('error級別')  # 40
# logging.critical('critical級別')  # 50
'''預設記錄的級別在30及以上''

# 簡單使用
import logging
file_handler = logging.FileHandler(filename='x1.log', mode='a', encoding='utf-8',)
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
    handlers=[file_handler,],
    level=logging.ERROR
)
logging.error('日誌模組很好學 不要自己嚇自己')
"""
1.如何控制日誌輸入的位置
    想在檔案和終端中同時列印
2.不同位置如何做到不同的日誌格式
    檔案詳細一些 終端簡單一些
"""

日誌模組詳細介紹

import logging


# 1.logger物件:負責產生日誌
logger = logging.getLogger('轉賬記錄')
# 2.filter物件:負責過濾日誌(直接忽略)
# 3.handler物件:負責日誌產生的位置
hd1 = logging.FileHandler('a1.log',encoding='utf8')  # 產生到檔案的
hd2 = logging.FileHandler('a2.log',encoding='utf8')  # 產生到檔案的
hd3 = logging.StreamHandler()  # 產生在終端的
# 4.formatter物件:負責日誌的格式
fm1 = logging.Formatter(
    fmt='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
)
fm2 = logging.Formatter(
    fmt='%(asctime)s - %(name)s %(message)s',
    datefmt='%Y-%m-%d',
)
# 5.繫結handler物件
logger.addHandler(hd1)
logger.addHandler(hd2)
logger.addHandler(hd3)
# 6.繫結formatter物件
hd1.setFormatter(fm1)
hd2.setFormatter(fm2)
hd3.setFormatter(fm1)
# 7.設定日誌等級
logger.setLevel(30)
# 8.記錄日誌
logger.debug('寫了半天 好累啊 好熱啊')

配置字典

########  這裡核心就在於複製貼上(cv大法)
import logging
import logging.config

standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]' #其中name為getlogger指定的名字

simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

logfile_path = 'a3.log'
# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
    },
    'filters': {},  # 過濾日誌
    'handlers': {
        #列印到終端的日誌
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 列印到螢幕
            'formatter': 'simple'
        },
        #列印到檔案的日誌,收集info及以上的日誌
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 儲存到檔案
            'formatter': 'standard',
            'filename': logfile_path,  # 日誌檔案
            'maxBytes': 1024*1024*5,  # 日誌大小 5M
            'backupCount': 5,
            'encoding': 'utf-8',  # 日誌檔案的編碼,再也不用擔心中文log亂碼了
        },
    },
    'loggers': {
        #logging.getLogger(__name__)拿到的logger配置  空字串作為鍵 能夠相容所有的日誌
        '': {
            'handlers': ['default', 'console'],  # 這裡把上面定義的兩個handler都加上,即log資料既寫入檔案又列印到螢幕
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)傳遞
        },  # 當鍵不存在的情況下 (key設為空字串)預設都會使用該k:v配置
    },
}


# 使用配置字典
logging.config.dictConfig(LOGGING_DIC)  # 自動載入字典中的配置
logger1 = logging.getLogger('xxx')
logger1.debug('好好的 不要浮躁 努力就有收穫')