首页 > 解决方案 > How to increment integer variable within logging statement?

问题描述

I am using python 3.6 logging module and trying to print a counter which should increment with every logging statement. I have in working now as shown in code below.

Code

  1 #!/something/bin/python
  2
  3 import logging
  4
  5 logger = logging.getLogger(__name__)
  6 l_level = 'INFO'
  7 l_level = eval("logging." + l_level.upper())
  8 logger.setLevel(l_level)
  9
 10 handler = logging.StreamHandler()
 11 handler.setLevel(l_level)
 12
 13 formatter = logging.Formatter('%(message)s')
 14 handler.setFormatter(formatter)
 15 logger.addHandler(handler)
 16
 17 i = 0
 18 i += 1; logger.info("{} Started".format(i))
 19 #logger.info("{} Started".format(i += 1)) # What I am trying to do
 20

So it works as I want if I increment i every time before I use logging statement. (line 18)

Question: Is there any way I can increment i within logging statement itself?

Tried: I tried using i += 1 and i = i + 1 (line 19) but it doesn't work that way. Also checked documentation for logging module but couldn't find anything that I can use here.

Error I get when I tried using i += 1 and i = i + 1:

  File "./test_2.py", line 19
    i += 1; logger.info("{} Started".format(i += 1))
                                               ^
  File "./test_2.py", line 19, in <module>
    i += 1; logger.info("{} Started".format(i = i + 1))

So now trying to find if there is any other way (specific to logging module or any other hack) to do this. Any help or suggestions are welcome. Thank you in for your time reading this.

标签: python-3.xpython-logging

解决方案


推荐阅读