How to enter variables into the log formatter?

I have now:

FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S', filename=LOGFILE, level=getattr(logging, options.loglevel.upper()))

... which works great, however I am trying to do:

FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'

and it just throws out keyerrors, although MYVARdefined.

Is there a workaround? MYVAR- this is a constant, so it would be a shame to skip it every time I start the recorder.

Thank!

+7
source share
4 answers

You can use a custom filter :

import logging

MYVAR = 'Jabberwocky'


class ContextFilter(logging.Filter):
    """
    This is a filter which injects contextual information into the log.
    """
    def filter(self, record):
        record.MYVAR = MYVAR
        return True

FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S')

logger = logging.getLogger(__name__)
logger.addFilter(ContextFilter())

logger.warning("'Twas brillig, and the slithy toves")

gives

Jabberwocky 24/04/2013 20:57:31 - WARNING - 'Twas brillig, and the slithy toves
+11
source

You can use custom Filter, as it says unutbu, or you can use LoggerAdapter:

import logging

logger = logging.LoggerAdapter(logging.getLogger(__name__), {'MYVAR': 'Jabberwocky'})

FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S')

logger.warning("'Twas brillig, and the slithy toves")

which gives

Jabberwocky 04/25/2013 07:39:52 - WARNING - 'Twas brillig, and slithy toves

:

import logging

logger = logging.getLogger(__name__)

FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S')

logger.warning("'Twas brillig, and the slithy toves", extra={'MYVAR': 'Jabberwocky'})

.

MYVAR , LoggerAdapter , Filter .

+5
locals()
FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'

locals() , . , . , . , , . "globals()", ... , , " MYVAR" , FORMAT

0

, , , , :

FORMAT = '{} %(asctime)s - %(levelname)s - %(message)s'.format(MYVAR)

Using this method does not require the implementation of custom classes, and you do not need to worry about methods that are not defined for various classes ( LoggerAdapterand CustomAdapter), such as addHandler(). Admittedly, this is probably less Pythonic, but it worked as a quick fix for me.

0
source

All Articles