tips:
import logging# 日志記錄最低輸出級(jí)別設(shè)置logger = logging.getLogger() logger.setLevel(logging.DEBUG) # Logging記錄到文件fh = logging.FileHandler("test.log", mode='w')logger.addHandler(fh) # 將logger添加到handler里面# Logging記錄格式以及設(shè)置formatter = logging.Formatter("%(asctime)s - %(message)s") # 記錄時(shí)間和消息fh.setFormatter(formatter) # 此處設(shè)置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")
2019-03-18 21:39:37,260 - this is info2019-03-18 21:39:37,260 - this is debug2019-03-18 21:39:37,260 - this is warning2019-03-18 21:39:37,260 - this is error2019-03-18 21:39:37,260 - this is critical
Flask在0.3版本后就有了日志工具logger。
from flask import Flaskapp = Flask(__name__)app.logger.debug('A value for debugging')app.logger.warning('A warning occurred (%d apples)', 42)app.logger.error('An error occurred')if __name__ == "__main__": app.run()
import loggingfrom flask import Flaskapp = Flask(__name__)handler = logging.FileHandler(filename="test.log", encoding='utf-8')handler.setLevel("DEBUG")format_ ="%(asctime)s[%(name)s][%(levelname)s] :%(levelno)s: %(message)s"formatter = logging.Formatter(format_)handler.setFormatter(formatter)app.logger.addHandler(handler)if __name__ == "__main__": app.run()
import loggingimport logging.configfrom flask import Flasklogger_conf ={ 'version': 1, 'formatters': {'default': { 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s', }}, 'handlers': {'wsgi': { 'class': 'logging.StreamHandler', 'stream': 'ext://flask.logging.wsgi_errors_stream', 'formatter': 'default' }}, 'root': { 'level': 'INFO', 'handlers': ['wsgi'] } }app = Flask(__name__)logging.config.dictConfig(logger_conf)if __name__ == "__main__": app.run()
import loggingimport logging.configfrom flask import current_app, Flasklogger_conf ={ 'version': 1, 'formatters': {'default': { 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s', }}, 'handlers': {'wsgi': { 'class': 'logging.StreamHandler', 'stream': 'ext://flask.logging.wsgi_errors_stream', 'formatter': 'default' }}, 'root': { 'level': 'INFO', 'handlers': ['wsgi'] }}def create_app(): app = Flask(__name__) # 方法一日志設(shè)置 handler = logging.FileHandler(filename="test.log", encoding='utf-8') handler.setLevel("DEBUG") format_ ="%(asctime)s[%(name)s][%(levelname)s] :%(levelno)s: %(message)s" formatter = logging.Formatter(format_) handler.setFormatter(formatter) app.logger.addHandler(handler) # 方法二日志設(shè)置 # logging.config.dictConfig(logger_conf) return app app = create_app()@app.route("/", methods=["GET"])def test(): current_app.logger.info("this is info") current_app.logger.debug("this is debug") current_app.logger.warning("this is warning") current_app.logger.error("this is error") current_app.logger.critical("this is critical") return "ok"if __name__ == "__main__": app.run()
請(qǐng)求http://127.0.0.1:5000 輸出到test.log內(nèi)容2019-03-18 22:02:58,718[flask.app][WARNING] :30: this is warning2019-03-18 22:02:58,718[flask.app][ERROR] :40: this is error2019-03-18 22:02:58,719[flask.app][CRITICAL] :50: this is critical2019-03-18 22:04:03,991[flask.app][WARNING] :30: this is warning2019-03-18 22:04:03,992[flask.app][ERROR] :40: this is error2019-03-18 22:04:03,992[flask.app][CRITICAL] :50: this is critical
-----app│ │ │ factoty.py-----config| || config.yaml| logging.yamlrun.py
version: 1disable_existing_loggers: False# 定義日志輸出格式,可以有多種格式輸出formatters: simple: format: "%(message)s" error: format: "%(asctime)s [%(name)s] [%(levelname)s] :%(levelno)s: %(message)s"# 定義不同的handler,輸出不同等級(jí)的日志消息handlers: console: class: logging.StreamHandler # 輸出到控制臺(tái) level: DEBUG formatter: simple stream: ext://flask.logging.wsgi_errors_stream # 監(jiān)聽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: error filename: ./logs/errors.log maxBytes: 10485760 # 10MB backupCount: 20 encoding: utf8# 啟用handlerroot: level: INFO handlers: [console,info_file_handler,error_file_handler]
COMMON: &common # app設(shè)置 DEBUG: False TESTING: False THREADED: False SECRET_KEY: insecure # 日志配置文件路徑 LOGGING_CONFIG_PATH: ./config/logging.yaml # 日志文件存放位置 LOGGING_PATH: ./logs DEVELOPMENT: &development <<: *common DEBUG: True ENV: devTESTING: &testing <<: *common ENV: test TESTING: True PRODUCTION: &production <<: *common ENV: prod SECRET_KEY: shouldbereallysecureatsomepoint
import loggingimport logging.configimport yamlimport osfrom flask import Flaskdef create_app(config_name=None, config_path=None): app = Flask(__name__) # 讀取配置文件 if not config_path: pwd = os.getcwd() config_path = os.path.join(pwd, 'config/config.yaml') if not config_name: config_name = 'PRODUCTION' conf = read_yaml(config_name, config_path) app.config.update(conf) if not os.path.exists(app.config['LOGGING_PATH']): # 日志文件目錄 os.mkdir(app.config['LOGGING_PATH']) # 日志設(shè)置 with open(app.config['LOGGING_CONFIG_PATH'], 'r', encoding='utf-8') as f: dict_conf = yaml.safe_load(f.read()) logging.config.dictConfig(dict_conf) # 載入日志配置 return app def read_yaml(config_name, config_path): """ config_name:需要讀取的配置內(nèi)容 config_path:配置文件路徑 """ if config_name and config_path: with open(config_path, 'r', encoding='utf-8') as f: conf = yaml.safe_load(f.read()) if config_name in conf.keys(): return conf[config_name.upper()] else: raise KeyError('未找到對(duì)應(yīng)的配置信息') else: raise ValueError('請(qǐng)輸入正確的配置名稱或配置文件路徑')
from app import factoryapp = factory.create_app(config_name='DEVELOPMENT')if __name__ == "__main__": app.run()
flask.app
的日志。from flask import current_app,Blueprintbp = Blueprint("test", __name__, url_prefix='/test')@bp.route('',methods=["GET"])def test(): current_app.logger.info("this is info") current_app.logger.debug("this is debug") current_app.logger.warning("this is warning") current_app.logger.error("this is error") current_app.logger.critical("this is critical") return "ok"# 輸出日志# 2019-03-18 22:02:58,718[flask.app][WARNING] :30: this is warning# 2019-03-18 22:02:58,718[flask.app][ERROR] :40: this is error# 2019-03-18 22:02:58,719[flask.app][CRITICAL] :50: this is critical# 2019-03-18 22:04:03,991[flask.app][WARNING] :30: this is warning# 2019-03-18 22:04:03,992[flask.app][ERROR] :40: this is error# 2019-03-18 22:04:03,992[flask.app][CRITICAL] :50: this is critical
import loggingfrom flask import Blueprintbp = Blueprint("test", __name__, url_prefix='/test')logger = logging.getLogger(__name__) #返回一個(gè)新的以文件名為名的logger@bp.route('',methods=["GET"])def test(): logger.info("this is info") logger.debug("this is debug") logger.warning("this is warning") logger.error("this is error") logger.critical("this is critical") return "ok" # 輸出日志# 2019-03-20 22:05:44,705 [app.test] [ERROR] :40: this is error# 2019-03-20 22:05:44,705 [app.test] [CRITICAL] :50: this is critical
聯(lián)系客服