1. 程式人生 > 實用技巧 >【Python】常用模組logging模組配置魔板 basicConfig & logging_dict

【Python】常用模組logging模組配置魔板 basicConfig & logging_dict

1、日誌級別與配置

import logging

# 一:日誌配置
logging.basicConfig(
    # 1、日誌輸出位置:1、終端 2、檔案
    # filename='access.log', # 不指定,預設列印到終端

    # 2、日誌格式
    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',

    # 3、時間格式
    datefmt='%Y-%m-%d %H:%M:%S %p',

    # 4、日誌級別
    # critical => 50
    # error => 40
    # warning => 30
    # info => 20
    # debug => 10
    level=30,
)

# 二:輸出日誌
logging.debug('除錯debug')
logging.info('訊息info')
logging.warning('警告warn')
logging.error('錯誤error')
logging.critical('嚴重critical')

'''
# 注意下面的root是預設的日誌名字
WARNING:root:警告warn
ERROR:root:錯誤error
CRITICAL:root:嚴重critical
'''

  

2、日誌配置字典

"""
logging配置
"""

import os

# 1、定義三種日誌輸出格式,日誌中可能用到的格式化串如下
# %(name)s Logger的名字
# %(levelno)s 數字形式的日誌級別
# %(levelname)s 文字形式的日誌級別
# %(pathname)s 呼叫日誌輸出函式的模組的完整路徑名,可能沒有
# %(filename)s 呼叫日誌輸出函式的模組的檔名
# %(module)s 呼叫日誌輸出函式的模組名
# %(funcName)s 呼叫日誌輸出函式的函式名
# %(lineno)d 呼叫日誌輸出函式的語句所在的程式碼行
# %(created)f 當前時間,用UNIX標準的表示時間的浮 點數表示
# %(relativeCreated)d 輸出日誌資訊時的,自Logger建立以 來的毫秒數
# %(asctime)s 字串形式的當前時間。預設格式是 “2003-07-08 16:49:45,896”。逗號後面的是毫秒
# %(thread)d 執行緒ID。可能沒有
# %(threadName)s 執行緒名。可能沒有
# %(process)d 程序ID。可能沒有
# %(message)s使用者輸出的訊息

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

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

test_format = '%(asctime)s] %(message)s'

# 3、日誌配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
        'test': {
            'format': test_format
        },
    },
    'filters': {},
    'handlers': {
        #列印到終端的日誌
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 列印到螢幕
            'formatter': 'simple'
        },
        #列印到檔案的日誌,收集info及以上的日誌
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 儲存到檔案,日誌輪轉
            'formatter': 'standard',
            # 可以定製日誌檔案路徑
            # BASE_DIR = os.path.dirname(os.path.abspath(__file__))  # log檔案的目錄
            # LOG_PATH = os.path.join(BASE_DIR,'a1.log')
            'filename': 'a1.log',  # 日誌檔案
            'maxBytes': 1024*1024*5,  # 日誌大小 5M
            'backupCount': 5,
            'encoding': 'utf-8',  # 日誌檔案的編碼,再也不用擔心中文log亂碼了
        },
        'other': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',  # 儲存到檔案
            'formatter': 'test',
            'filename': 'a2.log',
            'encoding': 'utf-8',
        },
    },
    'loggers': {
        #logging.getLogger(__name__)拿到的logger配置
        '': {
            'handlers': ['default', 'console'],  # 這裡把上面定義的兩個handler都加上,即log資料既寫入檔案又列印到螢幕
            'level': 'DEBUG', # loggers(第一層日誌級別關限制)--->handlers(第二層日誌級別關卡限制)
            'propagate': False,  # 預設為True,向上(更高level的logger)傳遞,通常設定為False即可,否則會一份日誌向上層層傳遞
        },
        '專門的採集': {
            'handlers': ['other',],
            'level': 'DEBUG',
            'propagate': False,
        },
    },
}

  3、使用

import settings

# !!!強調!!!
# 1、logging是一個包,需要使用其下的config、getLogger,可以如下匯入
# from logging import config
# from logging import getLogger

# 2、也可以使用如下匯入
import logging.config # 這樣連同logging.getLogger都一起匯入了,然後使用字首logging.config.

# 3、載入配置
logging.config.dictConfig(settings.LOGGING_DIC)

# 4、輸出日誌
logger1=logging.getLogger('使用者交易')
logger1.info('egon兒子alex轉賬3億冥幣')

# logger2=logging.getLogger('專門的採集') # 名字傳入的必須是'專門的採集',與LOGGING_DIC中的配置唯一對應
# logger2.debug('專門採集的日誌')