python - How to log number with commas as thousands separators? -
the time has come convert prints logging calls in library i'm maintaining. of print calls using str.format
, (simplified):
>>> n = 4000000 >>> print(f"this bird wouldn't voom if put {n:,} volts through it!") bird wouldn't voom if put 4,000,000 volts through it!
when try log it:
>>> log.warning("this bird wouldn't voom if put %d, volts through it!", n) warning:root:this bird wouldn't voom if put 4000000, volts through it!
seems not specifying thousands separator correctly. how specify thousands separator when using %-formatting syntax python's stdlib logging module necessitates?
currently using workaround, give desired output, seems wrong since variable formatted first using str.format
, formatted string again, instead of logging number directly:
>>> log.warning("this bird wouldn't voom if put %s volts through it!", format(n, ',')) warning:root:this bird wouldn't voom if put 4,000,000 volts through it!
that's limitation logging
, it's mentioned in (at least 1 place in) documentation:
logging.debug(msg, *args, **kwargs)
logs message level
debug
on root logger. msg message format string, , args arguments mergedmsg
using string formatting operator. (note means can use keywords in format string, single dictionary argument.)
(emphasis mine)
but string formatting operator %
doesn't support thousand seperators.
you adapt recipe official cookbook
:
import logging class message(object): def __init__(self, fmt, args): self.fmt = fmt self.args = args def __str__(self): return self.fmt.format(*self.args) class styleadapter(logging.loggeradapter): def __init__(self, logger, extra=none): super(styleadapter, self).__init__(logger, or {}) def log(self, level, msg, *args, **kwargs): if self.isenabledfor(level): msg, kwargs = self.process(msg, kwargs) self.logger._log(level, message(msg, args), (), **kwargs) logger = styleadapter(logging.getlogger(__name__)) def main(): # changed logger.warning("this bird wouldn't voom if put {:,} volts through it!", 4000000) if __name__ == '__main__': logging.basicconfig(level=logging.debug) main()
warning:__main__:
bird wouldn't voom if put 4,000,000 volts through it!
this copied verbatim (i changed message) last example in "use of alternative formatting styles" section.
personally go format(n, ',')
solution. may not perfect doesn't require setting custom loggeradapter
print different thousand seperator.
Comments
Post a Comment