Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to print to stdout or stderr in Django data migrations? If so, how?

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.

like image 618
Piotr Ćwiek Avatar asked May 05 '16 15:05

Piotr Ćwiek


2 Answers

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')
like image 78
Pratyush Avatar answered Sep 21 '22 07:09

Pratyush


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.

like image 31
Marshall X Avatar answered Sep 22 '22 07:09

Marshall X