PyDev unittesting: How to capture text logged to a logging.Logger in “Captured Output”

后端 未结 7 2145
青春惊慌失措
青春惊慌失措 2020-12-07 20:08

I am using PyDev for development and unit-testing of my Python application. As for unit-testing, everything works great except the fact that no content is logged to the logg

7条回答
  •  一整个雨季
    2020-12-07 20:42

    If you have different initaliser modules for test, dev and production then you can disable anything or redirect it in the initialiser.

    I have local.py, test.py and production.py that all inherit from common.y

    common.py does all the main config including this snippet :

        LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'django.server': {
                '()': 'django.utils.log.ServerFormatter',
                'format': '[%(server_time)s] %(message)s',
            },
            'verbose': {
                'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
            },
            'simple': {
                'format': '%(levelname)s %(message)s'
            },
        },
        'filters': {
            'require_debug_true': {
                '()': 'django.utils.log.RequireDebugTrue',
            },
        },
        'handlers': {
            'django.server': {
                'level': 'INFO',
                'class': 'logging.StreamHandler',
                'formatter': 'django.server',
            },
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'simple'
            },
            'mail_admins': {
                'level': 'ERROR',
                'class': 'django.utils.log.AdminEmailHandler'
            }
        },
        'loggers': {
            'django': {
                'handlers': ['console'],
                'level': 'INFO',
                'propagate': True,
            },
            'celery.tasks': {
                'handlers': ['console'],
                'level': 'DEBUG',
                'propagate': True,
            },
            'django.server': {
                'handlers': ['django.server'],
                'level': 'INFO',
                'propagate': False,
            },
        }
    

    Then in test.py I have this:

    console_logger = Common.LOGGING.get('handlers').get('console')
    console_logger['class'] = 'logging.FileHandler
    console_logger['filename'] = './unitest.log
    

    This replaces the console handler with a FileHandler and means still get logging but I do not have to touch the production code base.

提交回复
热议问题