import logging def log_system_init(logfile): "初始化日誌系統,同時將日誌信息輸出到控制檯和logfile日誌文件" root = logging.getLogger() root.setLevel(logging.NOTSET) filehandler = logging.FileHandler(logfile, "a",encoding='utf-8') filehandler.setLevel(logging.INFO) consolehandler = logging.StreamHandler() consolehandler.setLevel(logging.INFO) formatter0 = logging.Formatter("%(asctime)s %(levelname)s: %(message)s", datefmt='%H:%M:%S') formatter1 = logging.Formatter("%(asctime)s %(filename)s [line:%(lineno)d] - %(levelname)s: %(message)s", datefmt='%Y-%m-%d %H:%M:%S') filehandler.setFormatter(formatter1) consolehandler.setFormatter(formatter0) root.addHandler(filehandler) root.addHandler(consolehandler) return def log_critical(msg): "輸出錯誤信息" logging.critical(msg) def log_error(msg): "輸出錯誤信息" logging.error(msg) def log_warn(msg): # 經常使用的方法 "輸出警告信息" logging.warn(msg) def log_info(msg): # 經常使用的方法 "輸出info信息" logging.info(msg) def log_debug(msg): logging.debug(msg) if __name__ == '__main__': log_system_init("1.log") log_critical(u"好的...") log_error(u"critical log...") log_warn(u"critical log...") log_info(u"critical log...") log_debug(u"critical log...")