一、
無論對 logging.getLogger('someLogger')
進行多少次調用,都會返回同一個 logger 對象的引用。不僅在同一個模塊內如此,只要是在同一個 Python 解釋器進程中,跨模塊調用也是一樣。同樣是引用同一個對象,應用程序也可以在一個模塊中定義和配置一個父 logger,而在另一個單獨的模塊中創建(但不配置)子 logger,對於子 logger 的所有調用都會傳給父 logger。
參考鏈接:https://docs.python.org/zh-cn/3/howto/logging-cookbook.html
二、
問題:python 中封裝日志 logging,為何打印行號固定在同一行?
答:打印的行號是調用 logger 對象的所在行,所以自己進行封裝時,應該返回 logger 對象,再調用相應logger.info、logger.debug等方法。
參考鏈接:https://testerhome.com/topics/26827
三、代碼示例:
#!/usr/bin/env python # coding:utf-8 import logging,time import pathlib from src.utils.config import Config def get_logger(log_path=None): # log_path是存放日志的路徑,如果不存在這個logs文件夾,那么需要創建出來。 if not log_path: conf = Config() log_path = conf.log_path else: log_path = pathlib.Path(log_path) if not log_path.exists(): log_path.mkdir() logname = str(log_path.joinpath('%s.log'%time.strftime('%Y_%m_%d'))) logger = logging.getLogger() logger.setLevel(logging.DEBUG) # 日志輸出格式 formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') # 創建一個FileHandler,存儲日志文件 fh = logging.FileHandler(logname, encoding='utf-8') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) # 創建一個StreamHandler,用於輸出到控制台 sh = logging.StreamHandler() sh.setLevel(logging.DEBUG) sh.setFormatter(formatter)
# 如果不判斷是否為空,那么在多次調用函數get_logger函數后,會添加多個handler到logger.handlers中,導致出現日志重復輸出問題。
# 參考鏈接:https://www.cnblogs.com/huang-yc/p/9209096.html if not logger.handlers: logger.addHandler(sh) logger.addHandler(fh) return logger if __name__ == '__main__': log_path = "./log" log = get_logger(log_path) log.info(u'基礎信息') log.debug(u'調試信息') log.warning(u'警告信息') log.error(u'錯誤信息')
測試代碼bconfig.py
#!/usr/bin/env python # coding:utf-8 if __name__ == "__main__": from log import get_logger log_path = '/root/AutotestV2/log' log = get_logger(log_path) log.info("run test")
運行測試代碼bconfig.py結果如下:
可以看到打印出了log.info("run test")所在文件和行號。
[root@localhost utils]# python bconfig.py 2022-01-25 18:54:42,386 bconfig.py[line:9] INFO run test