寫一個簡單日誌器<logging>
阿新 • • 發佈:2019-05-03
oot root == open 消息 inf port span hand
import logging my_logger = logging.getLogger()#默認不傳參數為root #將日誌寫入到文件中去 fn = logging.FileHandler("my.log") #設置等級 fn.setLevel(logging.INFO) #格式化輸出:異常產生時間、級別、異常消息等 formatter = logging.Formatter( "時間:%(asctime)s" "日誌級別:%(levelname)s" "日誌消息:%(message)s" "日誌名稱:%(name)s" ) fn.setFormatter(formatter) #生效 my_logger.addHandler(fn) if __name__ == ‘__main__‘: try: a = 1/0 except Exception as e: my_logger.error(e) with open("my.log","r") as f: print(f.read())
控制臺結果:
時間:2019-05-03 19:37:56,145日誌級別:ERROR日誌消息:division by zero日誌名稱:root
寫一個簡單日誌器<logging>