django logging in script near manage.py - messages are just ignored

限于喜欢 提交于 2019-12-24 07:26:54

问题


I'm using Django 1.4.1. There's a script tmp.py in the same direcotry as manage.py, it does some routime operatons and is started from cron with command like python /path/to/project/tmp.py

Here is tmp.py:

import os
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MYPROJECT.settings")

if __name__ == "__main__":
    import logging
    logger = logging.getLogger('parser.test')
    logger.info('Hello, world')

This script makes a log entry, but this entry is just ignored by logger. When I put same 3 lines into any of my views, log entry appears in my log file as expected.

Logger config from setings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
    },
    'handlers': {
        'null': {
            'level':'DEBUG',
            'class':'django.utils.log.NullHandler',
        },
        'logfile': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': "/hosting/MYPROJECTS/logs/logfile",
            'maxBytes': 50000,
            'backupCount': 2,
            'formatter': 'standard',
        },
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
            'formatter': 'standard'
        },
    },
    'loggers': {
        'django': {
            'handlers':['console'],
            'propagate': True,
            'level':'WARN',
        },
        'django.db.backends': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'parser': {
            'handlers': ['console', 'logfile'],
            'level': 'DEBUG',
        },
    }
}

Why this logger works only in views? Maybe logger is still not configured after os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MYPROJECT.settings") in my tmp.py?


回答1:


I can't solve this problem but I found alternative solution: write a custom admin command instead of separate script near manage.py https://docs.djangoproject.com/en/dev/howto/custom-management-commands/ It logs works fine in admin commands.



来源:https://stackoverflow.com/questions/15340516/django-logging-in-script-near-manage-py-messages-are-just-ignored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!