參考:https://docs.python.org/2/library/logging.html
Logging模塊介紹
- 模塊:logging
- 類:
- Loggers:暴露直接給用戶使用的接口
- Handler:可以指定日志的輸出源(文件/console等)
- Filters:可以用于指定哪些日志可以輸出
- Formatters:指定日志的格式
我們通過下面的場景和源碼來理解Loggers/Handler/Formatters的作用和區(qū)別
場景一:輸出單一文件日志
logging.basicConfig(level=logging.INFO,
format='%(asctime)s > %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
filename='testlog.log',
filemode='w')
# 輸出日志
logging.info("test")
直接使用logging.info()通過root logger輸出求泰,且通過logging.basciConfig()可以指定root logger()的參數(shù)
場景二:輸出單一文件日志和控制臺(tái)日志
def __init_root_file_log():
logging.basicConfig(level=logging.INFO,
format='%(asctime)s > %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
filename='ui-test.log',
filemode='w')
return
def __init_console_log():
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
return
__init_root_file_log()
__init_console_log()
這里相比上一個(gè)場景萤厅,多了需要將日志輸出到控制臺(tái)橙困,python是通過向logger對象添加一個(gè)handler對象(StreamHandler對象)實(shí)現(xiàn)的:
logger.getLogger('')獲取root logger對象,然后addHandler(console)
場景三:輸出多個(gè)文件日志(附帶控制臺(tái)日志)
例如:相比場景二盟萨,我需要添加一個(gè)process_monitor.log,用來專門寫進(jìn)程監(jiān)控日志
loggers = {}
def init_log():
__init_root_file_log()
__init_process_log()
__init_console_log()
def __init_root_file_log():
logging.basicConfig(level=logging.INFO,
format='%(asctime)s > %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
filename='ui-test.log',
filemode='w')
return
def __init_console_log():
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
return
def __init_process_log():
loggerName = "processlog"
logger = logging.getLogger(loggerName)
fh = logging.FileHandler("process_monitor.log")
formatter = logging.Formatter("%(asctime)s > %(message)s")
fh.setFormatter(formatter)
logger.setLevel(logging.INFO)
logger.addHandler(fh)
loggers[loggerName] = logger
使用process_monitor.log輸出日志的調(diào)用方式如下:
# 在整個(gè)應(yīng)用開始時(shí)調(diào)用睡毒,初始化所有的logger對象
init_log()
# 輸出日志
loggers['processlog'].info("process test")
效果如下:
- 控制臺(tái)
- root logger:
- process_monitor.log:
?相比場景二的代碼谱秽,?多了__init_process_log()方法,它的處理如下:
1.logging.getLogger()獲取了一個(gè)logger對象耙蔑,這里參數(shù)可以是任意字符串
2.向logger對象添加了format對象和handler對象(FileHandler對象)
3.指定logger對象的日志級別
4.【非必須】將創(chuàng)建的logger對象添加到loggers這個(gè)dict對象中见妒,方便日志文件較多的時(shí)候?qū)θ罩緦ο筮M(jìn)行管理
上面的基本可以覆蓋大部分的硬盤日志需求,如果涉及網(wǎng)絡(luò)日志纵潦,可以看看Python的各種Handler實(shí)現(xiàn)徐鹤,這里后續(xù)如果有具體的業(yè)務(wù)場景的話,可以再講講