03.03.2012

logger

Correctly logs to stdout under runserver. Under mod_wsgi logs into apache error log and file named after python import path + function name. Call logger = get_logger() or logger = get_logger(request)
import inspect
import logging
import os
import os.path
import sys

from django.conf import settings
from django.http import HttpRequest

def obtain_request():
    ancestors = inspect.getouterframes(inspect.currentframe())
    for frame_record in ancestors:
        frame = frame_record[0]
        if 'request' in frame.f_locals:
            req = frame.f_locals['request']
            if isinstance(req, HttpRequest):
                return req

def get_logger(request=None):
    if request is None:
        request = obtain_request()
    stack = inspect.stack()
    logger_name = '%s.%s' % (stack[1][0].f_globals['__name__'], stack[1][3])
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.DEBUG)
    def addLogger(x):
        x.setLevel(logging.DEBUG)
        logger.addHandler(x)
    server = request.META.get('wsgi.file_wrapper', None) if request else None
    if server is None or server.__module__ == 'django.core.servers.basehttp':
        addLogger(logging.StreamHandler(sys.stdout))
    else:
        addLogger(logging.StreamHandler(request.META['wsgi.errors']))
        log_file = os.path.join(
            os.path.abspath(settings.PROJECT_ROOT),
            'logs', '%s.log' % logger_name)
        log_dir = os.path.dirname(log_file)
        if not os.path.exists(log_dir):
            os.mkdirs(log_dir)
        addLogger(logging.FileHandler(log_file))
    return logger

Комментариев нет: