We are using alembic to apply DB revision. I have configured the connection and it works as expected, except I am not able to make it use our customer logger.
We have our own logger class (derived from Python logging) which is used throughout the application, and I want alembic to use it instead of the default.
Is there any way I can pass a logger object of our class to it? I want it to print its own log using the format and handler that is defined in the custom logger.
I tried,
env file
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')
my script
self.alembic_cfg = alembic_config(self.alembic_ini_path, attributes={'configure_logger': False})
I also tried,
self.alembic_cfg.set_section_option("logger", "keys", "root")
Both of the above methods just disable its own logs.
To my knowledge, it is not possible to replace one logger with another. Is it something that you really need though?
I want it to print its own log using the format and handler that is defined in the custom logger.
As I understand it, logger has handlers and handlers have formatters. If you have a handler with a formatter you could just edit alembic.ini
and assign your handler to alembic logger.
ini
file[formatters] # existing section
keys = generic,pyraider # just add the name of your formatter
[formatter_pyraider]
class=tools.logger.PyraiderFormatter
ini
file[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
[logger_alembic] # existing section, what you want
level = INFO
handlers = pyraider # <---- add your handler, defined previously, here
qualname = alembic
Docs on alembic.ini
file.
https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
You might need to tweak some things but it should work as that's basically how python logging
module works.
More info on how to structure you ini
file for logging module
Official Python Docs
Hitchhiker's Guide
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With