Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change alembic logger

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.

like image 450
PyRaider Avatar asked Apr 24 '20 18:04

PyRaider


1 Answers

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.

  1. add formatter to formatters in ini file
[formatters]  # existing section
keys = generic,pyraider  # just add the name of your formatter
  1. define your custom formatter
[formatter_pyraider]
class=tools.logger.PyraiderFormatter
  1. add handler to handlers in ini file
[handlers]  # existing section
keys = console,pyraider  # just add the name of your handler
  1. define your custom 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
  1. assign handler to alembic logger
[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

like image 159
Tom Wojcik Avatar answered Sep 30 '22 05:09

Tom Wojcik