Python中的日志模块
最简单的用法:
import logging 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") #输出 WARNING:root:user [qianduoduo] attempted wrong password more than 3 times ERROR:root:logging error CRITICAL:root:logging critical #root 就是默认的用户名
重点:为什么上面debug和info没有输出,那是因为一个模块默认的日志级别是warning,比他级别低的就不会输出
把日志写到文件系统里
import logging logging.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 debug 2018-01-27 07:33:30 PM logging info 2018-01-27 07:33:30 PM user [qianduoduo] attempted wrong password more than 3 times 2018-01-27 07:33:30 PM logging error 2018-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 json import logging import logging.config import os def 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")