標籤:線程 logs 配置 ati handlers name main 格式 formatter
最簡單的用法:
import logginglogging.debug("logging debug")logging.info("logging info")logging.warning("user [qianduoduo] attempted wrong password more than 3 times")logging.error("logging error")logging.critical("logging critical")#輸出WARNING:root:user [qianduoduo] attempted wrong password more than 3 timesERROR:root:logging errorCRITICAL:root:logging critical #root 就是預設的使用者名稱
重點:為什麼上面debug和info沒有輸出,那是因為一個模組預設的記錄層級是warning,比他層級低的就不會輸出
把日誌寫到檔案系統裡
import logginglogging.basicConfig(filename=‘duoduo.log‘, level=logging.DEBUG, format=‘%(asctime)s %(message)s‘,#asctime字串形式的目前時間,message使用者輸出的訊息 datefmt=‘%Y-%m-%d %I:%M:%S %p ‘)logging.debug("logging debug")logging.info("logging info")logging.warning("user [qianduoduo] attempted wrong password more than 3 times")logging.error("logging error")logging.critical("logging critical")#輸出到檔案‘duoduo.log’2018-01-27 07:33:30 PM logging debug2018-01-27 07:33:30 PM logging info2018-01-27 07:33:30 PM user [qianduoduo] attempted wrong password more than 3 times2018-01-27 07:33:30 PM logging error2018-01-27 07:33:30 PM logging critical
format的日誌格式
|
|
Logger的名字 |
|
%(levelno)s |
數字形式的記錄層級 |
|
%(levelname)s |
文本形式的記錄層級 |
|
%(pathname)s |
調用日誌輸出函數的模組的完整路徑名,可能沒有 |
|
%(filename)s |
調用日誌輸出函數的模組的檔案名稱 |
|
%(module)s |
調用日誌輸出函數的模組名 |
|
%(funcName)s |
調用日誌輸出函數的函數名 |
|
%(lineno)d |
調用日誌輸出函數的語句所在的程式碼 |
|
%(created)f |
目前時間,用UNIX標準的表示時間的浮 點數表示 |
|
%(relativeCreated)d |
輸出日誌資訊時的,自Logger建立以 來的毫秒數 |
|
%(asctime)s |
字串形式的目前時間。預設格式是 “2003-07-08 16:49:45,896”。逗號後面的是毫秒 |
|
%(thread)d |
線程ID。可能沒有 |
|
%(threadName)s |
線程名。可能沒有 |
|
%(process)d |
進程ID。可能沒有 |
|
%(message)s |
使用者輸出的訊息 |
通過設定檔配置log
{ "version":1, "disable_existing_loggers":false, "formatters":{ "simple":{ "format":"%(asctime)s - %(name)s - %(levelname)s - %(message)s" } }, "handlers":{ "console":{ "class":"logging.StreamHandler", "level":"DEBUG", "formatter":"simple", "stream":"ext://sys.stdout" }, "info_file_handler":{ "class":"logging.handlers.RotatingFileHandler", "level":"INFO", "formatter":"simple", "filename":"logs/info.log", "maxBytes":10485760, "backupCount":20, "encoding":"utf8" }, "error_file_handler":{ "class":"logging.handlers.RotatingFileHandler", "level":"ERROR", "formatter":"simple", "filename":"logs/errors.log", "maxBytes":10485760, "backupCount":20, "encoding":"utf8" } }, "loggers":{ "my_module":{ "level":"DEBUG", "handlers":["info_file_handler"], "propagate":"no" } }, "root":{ "level":"INFO", "handlers":["console","info_file_handler","error_file_handler"] }}
在程式中引用
import jsonimport loggingimport logging.configimport osdef setup_logging(default_path="logging.json", default_level=logging.INFO, env_key="LOG_CFG"): path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, "r") as f: config = json.load(f) logging.config.dictConfig(config) else: logging.basicConfig(level=default_level)if __name__ == "__main__": setup_logging(default_path="logging.json")
Python中的日誌模組