import logging

from quixote import get_request, get_session

from qommon.logger import BotFilter

from hosts import Host

class Formatter(logging.Formatter):
    def format(self, record):
        request = get_request()

        record.address = request.get_environ('REMOTE_ADDR', '-')
        record.path = request.get_path()
        record.session_id = get_session().get_session_id() or '[nosession]'

        user = None
        host = Host.get_host_from_url()
        if not host:
            host = Host.select(lambda x: x.name == 'larpe')[0]
        if host:
            user = get_session().get_user(host.provider_id)
            if not user:
                user = get_session().get_user(host.saml2_provider_id)

        if user:
            user_id = user.id
        else:
            user_id = 'unlogged'
            if BotFilter.is_bot():
                user_id = 'bot'
        record.user_id = user_id

        return logging.Formatter.format(self, record)
