damd
damd

Reputation: 6957

Django logging of custom management commands

I have an app named main in my Django project. This app has a several management commands that I want to log, but nothing is showing up in stdout with the following configuration:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'log_to_stdout': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'stream': sys.stdout,
            },
        },
    'loggers': {
        'main': {
            'handlers': ['log_to_stdout'],
            'level': 'DEBUG',
            'propagate': True,
            }
        }
    }

What am I doing wrong? I've tried using my_project.main as well, but that didn't work either. I'm using 1.3.0 final.

Upvotes: 21

Views: 22179

Answers (3)

second
second

Reputation: 28637

you need to namespace your logger. currently you are logging to the root logger, which isn't caught by your handler, which is looking for main

rather than logging.debug("message"), you want

logger = logging.getLogger('main')
logger.debug("message")

Upvotes: 22

patrickn
patrickn

Reputation: 2561

If you are enrolling these custom commands with cron, you can "force" logging by just redirecting output to a text file.

* 12 * * * python /path/to/my/custom/command.py >> /path/to/my/logfile.txt

This will run a cron job at 12am every morning, and anything directed to stdout (like python print statements) will be dumped into this text file, concatenated on any existing text in the logfile.

If you're not using cron, just create a single shell script that runs all the scripts you need to run and manually direct them to the logfiles you want.

python /path/to/my/custom/command.py >> /path/to/my/logfile.txt

...and so on.

Upvotes: -5

jpic
jpic

Reputation: 33420

Setting "stream" to sys.stdout is not necessary. However, you should define a formatter:

Example:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'log_to_stdout': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
            },
        },
    'loggers': {
        'main': {
            'handlers': ['log_to_stdout'],
            'level': 'DEBUG',
            'propagate': True,
        }
    }
}

Upvotes: 4

Related Questions