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

4👍

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.

4👍

stderr should be used when something functionally breaks. IE, theres an actual error.

You should print to stdout any other time.

So if your migrations have any errors, I would redirect those to stderr. Other wise I think Marshall X answered correctly. If you need to refer back to anything that happened and you used print, well the information simply isn’t there.

I’d use logging.

2👍

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')

Leave a comment