python - 更改蒸馏器记录器
问题描述
我们正在使用 alembic 来应用数据库修订。我已经配置了连接,它按预期工作,但我无法让它使用我们的客户记录器。
我们有自己的记录器类(派生自 Python 日志记录),它在整个应用程序中使用,我希望 alembic 使用它而不是默认值。
有什么方法可以将我们类的记录器对象传递给它吗?我希望它使用自定义记录器中定义的格式和处理程序打印自己的日志。
我试过了,
环境文件
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from tools.logger import Logger
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.attributes.get('configure_logger', True):
fileConfig(config.config_file_name)
logger = Logger('alembic.env')
我的脚本
self.alembic_cfg = alembic_config(self.alembic_ini_path, attributes={'configure_logger': False})
我也试过,
self.alembic_cfg.set_section_option("logger", "keys", "root")
以上两种方法都只是禁用自己的日志。
解决方案
据我所知,不可能用另一个记录器替换一个记录器。这是你真正需要的东西吗?
我希望它使用自定义记录器中定义的格式和处理程序打印自己的日志。
据我了解,记录器有处理程序,处理程序有格式化程序。如果您有一个带有格式化程序的处理程序,您可以编辑alembic.ini
并将您的处理程序分配给 alembic 记录器。
- 将格式化程序添加到
ini
文件中的格式化程序
[formatters] # existing section
keys = generic,pyraider # just add the name of your formatter
- 定义您的自定义格式化程序
[formatter_pyraider]
class=tools.logger.PyraiderFormatter
- 将处理程序添加到
ini
文件中的处理程序
[handlers] # existing section
keys = console,pyraider # just add the name of your handler
- 定义您的自定义处理程序
[handler_pyraider] # new section, handler_<your_name>
class = tools.logger.PyraiderHandler
args = (sys.stderr,) # might need to play around with this one
level = INFO
formatter = pyraider
- 将处理程序分配给 alembic 记录器
[logger_alembic] # existing section, what you want
level = INFO
handlers = pyraider # <---- add your handler, defined previously, here
qualname = alembic
文件alembic.ini
存档。
https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
您可能需要调整一些东西,但它应该可以工作,因为这基本上就是 pythonlogging
模块的工作方式。
有关如何ini
为日志记录模块构建文件的更多信息
Official Python Docs
Hitchhiker's Guide
推荐阅读
- r - 使用 nls() 函数生成 von Bertalanffy 增长模型时出现“奇异梯度”错误
- keyboard - 如何将我的 debian 电脑完全设置为 dvorak?
- botframework - Botframework 可以对用户消息添加反应吗?
- python - python 3 请求。不可读的响应正文
- r - 带有 beta 家族的 glmmTMB
- c# - 如何在 C# 中使用 oledb 命令插入新行
- r - 在R中将重复测量旋转为宽格式
- java - Windows 批处理“dir”命令更改?
- reactjs - 如何同时将道具传递给两个组件?
- python - AttributeError:类型对象'Split'没有属性'Train'