# coding: utf-8

import json
import logging
import os
import sys

from ylog.context import get_log_context
from ylog.format import QloudJsonFormatter

from . import IS_DEVELOPMENT

_level = os.getenv('PROCU_LOGGING_LEVEL', 'WARNING')


logging.captureWarnings(capture=True)


class Formatter(QloudJsonFormatter):
    def format(self, record):
        record.message = record.getMessage()

        log_data = {'message': record.message, 'level': record.levelname}

        if record.exc_info:
            exc = logging.Formatter.formatException(self, record.exc_info)
            log_data['stackTrace'] = exc

        fields = {}

        log_context_fields = get_log_context()
        if log_context_fields:
            log_context_fields['logger'] = record.name
            fields['context'] = log_context_fields

        if fields:
            log_data['@fields'] = fields

        return json.dumps(log_data, ensure_ascii=False)


_handler = 'qloud_json'


if IS_DEVELOPMENT:
    _handler = 'console_text'


LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(asctime)s\t%(levelname)s\t%(name)s\t%(message)s',
            'datefmt': '%Y-%m-%d %H:%M:%S',
        },
        'message_only': {'format': '%(message)s'},
        'json': {'()': Formatter},
    },
    'handlers': {
        'console_text': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
        'qloud_json': {
            'class': 'logging.StreamHandler',
            'stream': sys.stdout,
            'formatter': 'json',
        },
    },
    'loggers': {
        'access_log': {
            'level': 'INFO',
            'handlers': [_handler],
            'propagate': False,
        },
        'django.request': {
            'level': _level,
            'handlers': [_handler],
            'propagate': False,
        },
        'django.db.backends': {
            'handlers': [_handler],
            'level': 'WARNING',
            'propagate': False,
        },
        'startrek_client.connection': {
            'handlers': [_handler],
            'level': 'WARNING',
            'propagate': False,
        },
        'py.warnings': {'handlers': [], 'level': 'ERROR', 'propagate': False},
    },
    'root': {'level': _level, 'handlers': [_handler]},
}

LOG_QUERY_THRESHOLD = 0.1
