[Python] How to log using style='{'

Discussão em 'Python' iniciado por Stack, Janeiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am using Python 3.8.10. I am trying to use the logging style '{'. From the documentation under formatters

    It states the following


    If the style is ‘%’, the message format string uses %()s styled string substitution; the possible keys are documented in LogRecord attributes. If the style is ‘{‘, the message format string is assumed to be compatible with str.format() (using keyword arguments), while if the style is ‘$’ then the message format string should conform to what is expected by string.Template.substitute().
    ​

    I am having a problem getting style='{' to work correctly. Specifically passing the keyword arguments it needs per the docs.

    import logging

    logger = logging.getLogger(__name__)

    formatter = logging.Formatter('{asctime} - {name} - {levelname} - {message}',style='{')

    scrnhandler = logging.StreamHandler()
    scrnhandler.setLevel(logging.INFO)
    scrnhandler.setFormatter(formatter)

    logger.addHandler(scrnhandler)
    logger.level = logging.INFO

    logger.info("plain message as base case") #<-- Works, no args passed

    mystr = "Input args: {0:f}".format(10) #<-- This is supposed to be str.format this is to be followed

    logger.info("Input args: {0:f}", 10) #<-- Does not work, I assume it wants a 'named argument'
    logger.info("Input args: {args[0]:f}", 10) #<-- Does not work,
    # I know the data goes into the LogRecord args attribute so tried that

    logger.info("Input args: {a:f}", a=10) #<-- Does not work, is looking for more args to parse


    I have not been able to find an example that shows how to use logging following this style, can someone help me figure out the nuance that am I missing to use this style of logging?

    Continue reading...

Compartilhe esta Página