python logging 日誌輸出 學習筆記 時間格式化
阿新 • • 發佈:2019-02-02
#coding:utf-8 # ======================================================================= # FuncName: console_out.py # Desc: output log to console and file # Date: 2016-02-19 17:32 # Author: johnny # ======================================================================= import logging def console_out(logFilename): ''' Output log to file and console ''' # Define a Handler and set a format which output to file logging.basicConfig( level = logging.DEBUG, # 定義輸出到檔案的log級別, format = '%(asctime)s %(filename)s : %(levelname)s %(message)s', # 定義輸出log的格式 datefmt = '%Y-%m-%d %A %H:%M:%S', # 時間 filename = logFilename, # log檔名 filemode = 'w') # 寫入模式“w”或“a” # Define a Handler and set a format which output to console console = logging.StreamHandler() # 定義console handler console.setLevel(logging.INFO) # 定義該handler級別 formatter = logging.Formatter('%(asctime)s %(filename)s : %(levelname)s %(message)s') #定義該handler格式 console.setFormatter(formatter) # Create an instance logging.getLogger().addHandler(console) # 例項化新增handler # Print information # 輸出日誌級別 logging.debug('logger debug message') logging.info('logger info message') logging.warning('logger warning message') logging.error('logger error message') logging.critical('logger critical message') if __name__ == "__main__": console_out('logging.log')
控制檯: