错误示范
1 2 3 4 5 6
| import logging
log = logging.getLogger() log.setLevel(logging.INFO) log.info("INFO INFO INFO") log.warning("这是WARN")
|
1 2 3
| # 输出 D:\workspace\investment\venv\Scripts\python.exe D:/workspace/python-common/basic/logging_test.py 这是WARN
|
没有输出INFO的日志级别。默认是WARN级别的日志,这里没有输出WARN说明没有设置成功。
设置一个handler
1 2 3 4 5 6 7 8
| import logging
if __name__ == '__main__': log = logging.getLogger() handler = logging.StreamHandler() log.addHandler(handler) log.setLevel(logging.INFO) log.info("这是INFO-1")
|
这时可以正常输出INFO了
logging.getLogger() 和 logging.getLogger(name)
1 2 3 4 5 6 7 8 9 10 11
| import logging
if __name__ == '__main__': log = logging.getLogger() handler = logging.StreamHandler() log.addHandler(handler) log.setLevel(logging.INFO) log.info("这是INFO-1")
logger = logging.getLogger() logger.info("这是INFO-2")
|
此时第二个logger也被设置了INFO级别了,查看源码:
可以看到名字为None时返回的是一个root对象,这也是为什么第二个logger也被修改的原因。
日志输出位置
常见的输出到控制台和文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import logging
if __name__ == '__main__': log = logging.getLogger("console-logger") handler = logging.StreamHandler() log.addHandler(handler) log.setLevel(logging.INFO) log.info("这是INFO-1")
log2 = logging.getLogger("file-logger") file_handler = logging.FileHandler("E:/test.log") log2.addHandler(file_handler) log2.setLevel(logging.WARNING) log2.info("这个不会被记录") log2.warning("警告警告~~~~")
|
设置格式
默认只是输出了message,这样子还不如直接用print()函数了。所以还需要格式化一下:
设置格式化要用到logging.Handler
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import logging
def print_name(logger, name): logger.info("name={}".format(name))
if __name__ == '__main__': log = logging.getLogger("console-logger") handler = logging.StreamHandler() handler.setFormatter(logging.Formatter("%(asctime)s %(filename)s %(funcName)s[line:%(lineno)d]%(levelname)s - %(message)s")) log.addHandler(handler) log.setLevel(logging.INFO) log.info("这是INFO-1") print_name(log, "happyjava")
|
输出效果:
formatter参数: