(四)Flask中yaml配置logger及logger使用

2019-10-10  本文已影响0人  python与数据分析

Python logging模块

Logging日志一共五个级别

日志级别: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
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]

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
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()

结果(自动创建日志)


上一篇下一篇

猜你喜欢

热点阅读