本文主要是介绍Flask中使用日志库loguru,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- README.md
- app.py
- config.py
- 参考资料
关于日志记录库loguru的介绍,具体可参见之前的博客:Python日志记录库——loguru
今天来介绍下,如何在Flask中使用loguru日志库。
README.md
This is a simple example of how to use loguru in your flask application
Just create a new InterceptHandler and add it to your app. Different settings should be configured in your config file, so that it is easy to change settings.
这是如何在您的Flask应用程序中使用 loguru 的简单示例
只需创建一个新的 InterceptHandler 并将其添加到您的应用程序中即可。需要在配置文件中配置不同的设置,以便于后续更改应用的设置。
Logging is then as easy as:
from loguru import loggerlogger.info("I am logging from loguru!")
app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import config
from loguru import logger
import loggingdb = SQLAlchemy()# create a custom handler
class InterceptHandler(logging.Handler):def emit(self, record):logger_opt = logger.opt(depth=6, exception=record.exc_info)logger_opt.log(record.levelno, record.getMessage())# application factory pattern
def create_app(config_name):app = Flask(__name__)app.config.from_object(config[config_name])config[config_name].init_app(app)db.init_app(app)# logging properties are defined in config.pylogger.start(app.config['LOGFILE'], level=app.config['LOG_LEVEL'], format="{time} {level} {message}",backtrace=app.config['LOG_BACKTRACE'], rotation='25 MB')#register loguru as handlerapp.logger.addHandler(InterceptHandler())# register Blueprints here# ...return app
config.py
import osbasedir = os.path.abspath(os.path.dirname(__file__))class Config(object):SECRET_KEY = os.environ.get('SECRET_KEY') or 'SUPER-SECRET'LOGFILE = "log.log"class DevelopmentConfig(Config):DEBUG = TrueLOG_BACKTRACE = TrueLOG_LEVEL = 'DEBUG'class ProductionConfig(Config):LOG_BACKTRACE = FalseLOG_LEVEL = 'INFO'config = {'development': DevelopmentConfig,'production': ProductionConfig,'default': DevelopmentConfig
}
参考资料
- https://gist.github.com/M0r13n/0b8c62c603fdbc98361062bd9ebe8153
- flask loguru简单示例
- Python自动化之使用loguru优雅输出日志
这篇关于Flask中使用日志库loguru的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!