1. 程式人生 > >python教程系列(三.2.8、log模組)

python教程系列(三.2.8、log模組)

在這裡插入圖片描述

  • 日誌級別

CRITICAL = 50 #FATAL = CRITICAL
ERROR = 40
WARNING = 30 #WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0 #不設定
  • 預設級別為warning,預設列印到終端

import logging

logging.debug('除錯debug')
logging.info('訊息info')
logging.warning('警告warn')
logging.error('錯誤error')
logging.critical('嚴重critical')

'''
WARNING:root:警告warn
ERROR:root:錯誤error
CRITICAL:root:嚴重critical
'''
  • 為logging模組指定全域性配置,針對所有logger有效,控制列印到檔案中

可在logging.basicConfig()函式中通過具體引數來更改logging模組預設行為,可用引數有
filename:用指定的檔名建立FiledHandler(後邊會具體講解handler的概念),這樣日誌會被儲存在指定的檔案中。
filemode:檔案開啟方式,在指定了filename時使用這個引數,預設值為“a”還可指定為“w”。
format:指定handler使用的日誌顯示格式。 
datefmt:指定日期時間格式。 
level:設定rootlogger(後邊會講解具體概念)的日誌級別 
stream:用指定的stream建立StreamHandler。可以指定輸出到sys.stderr,sys.stdout或者檔案,預設為sys.stderr。若同時列出了filename和stream兩個引數,則stream引數會被忽略。



#格式
%(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:使用者輸出的訊息
format引數中可能用到的格式化串:
%(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使用者輸出的訊息




#========使用
import logging
logging.basicConfig(filename='access.log',
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=10)

logging.debug('除錯debug')
logging.info('訊息info')
logging.warning('警告warn')
logging.error('錯誤error')
logging.critical('嚴重critical')





#========結果
access.log內容:
2017-07-28 20:32:17 PM - root - DEBUG -test:  除錯debug
2017-07-28 20:32:17 PM - root - INFO -test:  訊息info
2017-07-28 20:32:17 PM - root - WARNING -test:  警告warn
2017-07-28 20:32:17 PM - root - ERROR -test:  錯誤error
2017-07-28 20:32:17 PM - root - CRITICAL -test:  嚴重critical

part2: 可以為logging模組指定模組級的配置,即所有logger的配置
  • logging模組的Formatter,Handler,Logger,Filter物件

原理圖:

logger:產生日誌的物件
Filter:過濾日誌的物件
Handler:接收日誌然後控制列印到不同的地方,FileHandler用來列印到檔案中,StreamHandler用來列印到終端
Formatter物件:可以定製不同的日誌格式物件,然後繫結給不同的Handler物件使用,以此來控制不同的Handler的日誌格式



'''
critical=50
error =40
warning =30
info = 20
debug =10
'''


import logging

#1、logger物件:負責產生日誌,然後交給Filter過濾,然後交給不同的Handler輸出
logger=logging.getLogger(__file__)

#2、Filter物件:不常用,略

#3、Handler物件:接收logger傳來的日誌,然後控制輸出
h1=logging.FileHandler('t1.log') #列印到檔案
h2=logging.FileHandler('t2.log') #列印到檔案
h3=logging.StreamHandler() #列印到終端

#4、Formatter物件:日誌格式
formmater1=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',)

formmater2=logging.Formatter('%(asctime)s :  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',)

formmater3=logging.Formatter('%(name)s %(message)s',)


#5、為Handler物件繫結格式
h1.setFormatter(formmater1)
h2.setFormatter(formmater2)
h3.setFormatter(formmater3)

#6、將Handler新增給logger並設定日誌級別
logger.addHandler(h1)
logger.addHandler(h2)
logger.addHandler(h3)
logger.setLevel(10)

#7、測試
logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critical')

[複製程式碼](javascript:void(0); “複製程式碼”)

  • Logger與Handler的級別

logger是第一級過濾,然後才能到handler,我們可以給logger和handler同時設定level,但是需要注意的是

[複製程式碼](javascript:void(0); “複製程式碼”)

Logger is also the first to filter the message based on a level — if you set the logger to INFO, and all handlers to DEBUG, you still won't receive DEBUG messages on handlers — they'll be rejected by the logger itself. If you set logger to DEBUG, but all handlers to INFO, you won't receive any DEBUG messages either — because while the logger says "ok, process this", the handlers reject it (DEBUG < INFO).



#驗證
import logging


form=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',)

ch=logging.StreamHandler()

ch.setFormatter(form)
# ch.setLevel(10)
ch.setLevel(20)

l1=logging.getLogger('root')
# l1.setLevel(20)
l1.setLevel(10)
l1.addHandler(ch)

l1.debug('l1 debug')

[複製程式碼](javascript:void(0); “複製程式碼”)

  • Logger的繼承(瞭解)

[複製程式碼](javascript:void(0); “複製程式碼”)

import logging

formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',)

ch=logging.StreamHandler()
ch.setFormatter(formatter)


logger1=logging.getLogger('root')
logger2=logging.getLogger('root.child1')
logger3=logging.getLogger('root.child1.child2')


logger1.addHandler(ch)
logger2.addHandler(ch)
logger3.addHandler(ch)
logger1.setLevel(10)
logger2.setLevel(10)
logger3.setLevel(10)

logger1.debug('log1 debug')
logger2.debug('log2 debug')
logger3.debug('log3 debug')
'''
2017-07-28 22:22:05 PM - root - DEBUG -test:  log1 debug
2017-07-28 22:22:05 PM - root.child1 - DEBUG -test:  log2 debug
2017-07-28 22:22:05 PM - root.child1 - DEBUG -test:  log2 debug
2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test:  log3 debug
2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test:  log3 debug
2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test:  log3 debug
'''

[複製程式碼](javascript:void(0); “複製程式碼”)

  • logging應用

[複製程式碼](javascript:void(0); “複製程式碼”)

"""
logging配置
"""

import os
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'

id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'

# 定義日誌輸出格式 結束

logfile_dir = os.path.dirname(os.path.abspath(__file__))  # log檔案的目錄

logfile_name = 'all2.log'  # log檔名

# 如果不存在定義的日誌目錄就建立一個
if not os.path.isdir(logfile_dir):
    os.mkdir(logfile_dir)

# log檔案的全路徑
logfile_path = os.path.join(logfile_dir, logfile_name)

# 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)傳遞
        },
    },
}


def load_my_logging_cfg():
    logging.config.dictConfig(LOGGING_DIC)  # 匯入上面定義的logging配置
    logger = logging.getLogger(__name__)  # 生成一個log例項
    logger.info('It works!')  # 記錄該檔案的執行狀態

if __name__ == '__main__':
    load_my_logging_cfg()

[複製程式碼](javascript:void(0); “複製程式碼”)

[複製程式碼](javascript:void(0); “複製程式碼”)

"""
MyLogging Test
"""

import time
import logging
import my_logging  # 匯入自定義的logging配置

logger = logging.getLogger(__name__)  # 生成logger例項


def demo():
    logger.debug("start range... time:{}".format(time.time()))
    logger.info("中文測試開始。。。")
    for i in range(10):
        logger.debug("i:{}".format(i))
        time.sleep(0.2)
    else:
        logger.debug("over range... time:{}".format(time.time()))
    logger.info("中文測試結束。。。")

if __name__ == "__main__":
    my_logging.load_my_logging_cfg()  # 在你程式檔案的入口載入自定義logging配置
    demo()
注意注意注意:
#1、有了上述方式我們的好處是:所有與logging模組有關的配置都寫到字典中就可以了,更加清晰,方便管理


#2、我們需要解決的問題是:
    1、從字典載入配置:logging.config.dictConfig(settings.LOGGING_DIC)

    2、拿到logger物件來產生日誌
    logger物件都是配置到字典的loggers 鍵對應的子字典中的
    按照我們對logging模組的理解,要想獲取某個東西都是通過名字,也就是key來獲取的
    於是我們要獲取不同的logger物件就是
    logger=logging.getLogger('loggers子字典的key名')

    
    但問題是:如果我們想要不同logger名的logger物件都共用一段配置,那麼肯定不能在loggers子字典中定義n個key   
 'loggers': {    
        'l1': {
            'handlers': ['default', 'console'],  #
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)傳遞
        },
        'l2: {
            'handlers': ['default', 'console' ], 
            'level': 'DEBUG',
            'propagate': False,  # 向上(更高level的logger)傳遞
        },
        'l3': {
            'handlers': ['default', 'console'],  #
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)傳遞
        },

}

    
#我們的解決方式是,定義一個空的key
    'loggers': {
        '': {
            'handlers': ['default', 'console'], 
            'level': 'DEBUG',
            'propagate': True, 
        },

}

這樣我們再取logger物件時
logging.getLogger(__name__),不同的檔案__name__不同,這保證了列印日誌時標識資訊不同,但是拿著該名字去loggers裡找key名時卻發現找不到,於是預設使用key=''的配置
另外一個django的配置,瞄一眼就可以,跟上面的一樣
# logging_config.py
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        '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'
        },
        'collect': {
            'format': '%(message)s'
        }
    },
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        #列印到終端的日誌
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        #列印到檔案的日誌,收集info及以上的日誌
        'default': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',  # 儲存到檔案,自動切
            'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"),  # 日誌檔案
            'maxBytes': 1024 * 1024 * 5,  # 日誌大小 5M
            'backupCount': 3,
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        #列印到檔案的日誌:收集錯誤及以上的日誌
        'error': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',  # 儲存到檔案,自動切
            'filename': os.path.join(BASE_LOG_DIR, "xxx_err.log"),  # 日誌檔案
            'maxBytes': 1024 * 1024 * 5,  # 日誌大小 5M
            'backupCount': 5,
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        #列印到檔案的日誌
        'collect': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',  # 儲存到檔案,自動切
            'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"),
            'maxBytes': 1024 * 1024 * 5,  # 日誌大小 5M
            'backupCount': 5,
            'formatter': 'collect',
            'encoding': "utf-8"
        }
    },
    'loggers': {
        #logging.getLogger(__name__)拿到的logger配置
        '': {
            'handlers': ['default', 'console', 'error'],
            'level': 'DEBUG',
            'propagate': True,
        },
        #logging.getLogger('collect')拿到的logger配置
        'collect': {
            'handlers': ['console', 'collect'],
            'level': 'INFO',
        }
    },
}


# 用法:拿到倆個logger

logger = logging.getLogger(__name__) #線上正常的日誌
collect_logger = logging.getLogger("collect") #領導說,需要為領導們單獨定製領導們看的日誌

在這裡插入圖片描述