import logging

import dockerflow.logging

from olympia import core


def getLogger(name=None):
    """Wrap logging.getLogger to return a LoggerAdapter that adds extra common
    arguments to each log statement."""
    logger = logging.getLogger(name)
    return AmoLoggerAdapter(logger)


class AmoLoggerAdapter(logging.LoggerAdapter):
    """Adds the REMOTE_ADDR and USERNAME to every logging message's kwargs."""

    def __init__(self, logger, extra=None):
        super(AmoLoggerAdapter, self).__init__(logger, extra or {})

    def process(self, msg, kwargs):
        kwargs['extra'] = {
            'REMOTE_ADDR': core.get_remote_addr() or '',
            'USERNAME': getattr(core.get_user(), 'username', None) or '<anon>'
        }
        return msg, kwargs


class Formatter(logging.Formatter):
    """Formatter that makes sure REMOTE_ADDR and USERNAME are available."""

    def format(self, record):
        for name in 'REMOTE_ADDR', 'USERNAME':
            record.__dict__.setdefault(name, '')
        return super(Formatter, self).format(record)


class JsonFormatter(dockerflow.logging.JsonLogFormatter):
    """Like JsonLogFormatter, but with uid and remoteAddressChain set from
    current user and ip, following mozlog format.

    See Formatter above for the legacy, console version of this."""
    def format(self, record):
        record.__dict__['uid'] = record.__dict__.pop('USERNAME', '')
        record.__dict__['remoteAddressChain'] = record.__dict__.pop(
            'REMOTE_ADDR', '')
        return super(JsonFormatter, self).format(record)

@@ -341,12 +341,27 @@
  %22%22%22
-Adds
+%0A    Adapter adding
  the
@@ -416,16 +416,180 @@
 ge's
+%0A   
  kwargs
-.
+ extra dict, which in return will automatically be merged in every%0A    LogRecord nstance, making those properties available for the formatter(s)%0A    to use.%0A    
 %22%22%22%0A
@@ -1049,16 +1049,90 @@
 ailable.
+%0A%0A    Relies on AmoLoggerAdapter to make sure those variables will be set.
 %22%22%22%0A%0A   
@@ -1493,16 +1493,16 @@
 ormat.%0A%0A
-
     See 
@@ -1557,24 +1557,25 @@
 of this.%22%22%22%0A
+%0A
     def form

Improve docstrings slightly