python中如何把log輸入到檔案
阿新 • • 發佈:2018-11-02
import logging,os import time def getlogger(loggername='mylogger'): # 使用一個名字為mylogger的logger logger = logging.getLogger(loggername) # 設定logger的level為DEBUG logger.setLevel(logging.DEBUG) # 建立一個輸出日誌到控制檯的StreamHandler stream_handler = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s]:[%(filename)s]:%(name)s:%(levelname)s: %(message)s') stream_handler.setFormatter(formatter) # 給logger新增上handler logdir = os.path.dirname(__file__) print(logdir) # now = time.strftime("%Y-%m-%d %H_%M_%S", time.localtime()) # filename = '%s/%s.log'%(logdir,now) #把log輸出到當前目錄下交usk.log的檔案 filename = '%s/usk.log' % (logdir) print(filename) file_handler = logging.FileHandler(filename) file_handler.setFormatter(formatter) logger.addHandler(stream_handler)#把日誌列印到控制檯 logger.addHandler(file_handler) #把日誌列印到檔案 return logger #舉例檢視log的形式 logger = getlogger('get_log') import logging def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: #列印log的級別和錯誤資訊 logger.warning(e) main()