I've been looking for any guidelines on this but with no success. In a project I use Django data migrations quite often. They look more-or-less like the example from the docs. However, the operations are sometimes rather complex and it would be nice to have some console output summarizing the performed operations (i.e. what got deleted/created/rewired/etc. and why).
So the question is: is it OK to code such logging into a migration? If so, is it better to use Python's logging
module or just print
? In the former case, an additional configuration would probably be required to make those logs visible (in settings.py
?). In the latter case, would stderr
or stdout
be preferred?
The question could be extended to whether interactive input from user is permissible. Built-in schema migration facilities are apt to ask interactive data-related questions.
Custom management commands have recommended ways of providing console output, which is part of motivation behind this question.
I use logger in complex migrations.
For me, the print statements didn't show in the console until the migration was completed. The logger worked as expected.
I use this code:
import logging
def get_console_logger():
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.info("starting logger")
return logger
def python_actions(apps, schema_editor):
logger = get_console_logger()
# do usual migraiton stuff
logger.info('use logger as needed')
I think log is the way to go here. Since you are going to run the migrations on your server, it's better to save it to log so you can catch it whatever you want later.
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