Logging in Django

2020年04月30日

-

Leveling level from DEBUG, INFO, WARNING, ERROR, and to CRITICAL.

Test case 1:


settings.py:
# settings.py
LOGGING = {
    ...
    'handlers': {
        ...
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/logs/debug.log'
        }
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': True
        }
    }
}

view.py:
# view.py
logger = logging.getLogger('django')

def example_page(request, *args):
    if logger.isEnabledFor(logging.INFO):
        logger.info("args:")
        logger.info(args)

刷新页面

$ kubectl exec -it blog-deployment-*** tail /logs/debug.log
args:
(None,)

Test case 2:

settings.py:
# settings.py
LOGGING = {
    ...
    'handlers': {
        ...
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/logs/debug.log'
        }
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': True
        }
    }
}

view.py:
# view.py
logger = logging.getLogger('django')

def example_page(request, *args):
    if logger.isEnabledFor(logging.DEBUG):
        logger.info("args:")
        logger.info(args)

刷新页面

$ kubectl exec -it blog-deployment-*** tail /logs/debug.log
没有log

Test case 3:

settings.py:
# settings.py
LOGGING = {
    ...
    'handlers': {
        ...
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/logs/debug.log'
        }
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True
        }
    }
}

view.py:
# view.py
logger = logging.getLogger('django')

def example_page(request, *args):
    if logger.isEnabledFor(logging.DEBUG):
        logger.info("args:")
        logger.info(args)

刷新页面

$ kubectl exec -it blog-deployment-*** tail /logs/debug.log
args:
(None,)
Exception

Test case 4:

settings.py
# settings.py
LOGGING = {
    ...
    'handlers': {
        ...
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/logs/debug.log'
        }
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True
        }
    }
}

view.py:
# view.py
logger = logging.getLogger('django')

def example_page(request, *args):
    if logger.isEnabledFor(logging.INFO):
        logger.info("args:")
        logger.info(args)

刷新页面

$ kubectl exec -it blog-deployment-*** tail /logs/debug.log
args:
(None,)
Exception
log信息量更多


References

Logging HOWTO
-

Category: Python Tags: public

Upvote


Downvote