Python logging模块
Logging日志一共五个级别
- debug : 打印全部的日志,详细的信息,通常只出现在诊断问题上
- info : 打印info,warning,error,critical级别的日志,确认一切按预期运行
- warning : 打印warning,error,critical级别的日志,一个迹象表明,一些意想不到的事情发生了,或表明一些问题在
- 不久的将来(例如。磁盘空间低”),这个软件还能按预期工作
- error : 打印error,critical级别的日志,更严重的问题,软件没能执行一些功能
- critical : 打印critical级别,一个严重的错误,这表明程序本身可能无法继续运行
日志级别:CRITICAL >ERROR> WARNING > INFO> DEBUG> NOTSET
logging日志设置以及使用
import logging
# 日志记录最低输出级别设置
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# Logging记录到文件
fh = logging.FileHandler("test.log", mode='w')
logger.addHandler(fh) # 将logger添加到handler里面
#### Logging记录格式以及设置
formatter = logging.Formatter("%(asctime)s - %(message)s") # 记录时间和消息
fh.setFormatter(formatter) # 此处设置handler的输出格式
# Logging使用
logger.info("this is info")
logger.debug("this is debug")
logger.warning("this is warning")
logging.error("this is error")
logger.critical("this is critical")
输出test.log
2019-03-18 21:39:37,260 - this is info
2019-03-18 21:39:37,260 - this is debug
2019-03-18 21:39:37,260 - this is warning
2019-03-18 21:39:37,260 - this is error
2019-03-18 21:39:37,260 - this is critical
yaml配置logger
- 文件目录
-----app
│ │
│ factoty.py
-----config
| |
| config.yaml
| logging.yaml
run.py
- 编写logging.yaml
version: 1
disable_existing_loggers: False
# 定义日志输出格式,可以有多种格式输出
formatters:
simple:
format: "%(message)s"
error:
format: "%(asctime)s [%(name)s] [%(levelname)s] :%(levelno)s: %(message)s"
# 定义不同的handler,输出不同等级的日志消息
handlers:
console:
class: logging.StreamHandler # 输出到控制台
level: DEBUG
formatter: simple
stream: ext://flask.logging.wsgi_errors_stream # 监听flask日志
info_file_handler:
class: logging.handlers.RotatingFileHandler # 输出到文件
level: INFO
formatter: simple
filename: ./logs/info.log
maxBytes: 10485760 # 10MB
backupCount: 20 #most 20 extensions
encoding: utf8
error_file_handler:
class: logging.handlers.RotatingFileHandler # 输出到文件
level: ERROR
formatter: simple
filename: ./logs/errors.log
maxBytes: 10485760 # 10MB
backupCount: 20
encoding: utf8
# 启用handler
root:
level: INFO
handlers: [console,info_file_handler,error_file_handler]
- 编写Flask config.yaml
COMMON: &common
# app设置
DEBUG: False
TESTING: False
THREADED: False
SECRET_KEY: insecure
# 日志配置文件路径
LOGGING_CONFIG_PATH: ./config/logging.yaml
# 日志文件存放位置
LOGGING_PATH: ./logs
DEVELOPMENT: &development
<<: *common
DEBUG: True
ENV: dev
TESTING: &testing
<<: *common
ENV: test
TESTING: True
PRODUCTION: &production
<<: *common
ENV: prod
SECRET_KEY: shouldbereallysecureatsomepoint
- 运行文件(run.py)
from app import factory
app = factory.create_app(config_name='DEVELOPMENT')
app.logger.info('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')
if __name__ == "__main__":
app.run()
结果(自动创建日志)
网友评论