You can automatically add thread ids to your log statements using Python’s logging
module with LogRecord. LogRecord
provides 2 attributes for thread related information: threadName
and thread
.
%(thread)d : Thread ID (if available).
%(threadName)s : Thread name (if available).
For printing thread name:
from logging import getLogger, getLevelName, Formatter, StreamHandler
log = getLogger()
log.setLevel(getLevelName('INFO'))
log_formatter = Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s [%(threadName)s] ") # I am printing thread id here
console_handler = StreamHandler()
console_handler.setFormatter(log_formatter)
log.addHandler(console_handler)
log.info("Hi, how are you")
Sample output from above:
2014-10-19 18:18:29,644 [INFO] root: Hi, how are you [MainThread]
For printing thread id:
from logging import getLogger, getLevelName, Formatter, StreamHandler
log = getLogger()
log.setLevel(getLevelName('INFO'))
log_formatter = Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s [%(threadName)s] ") # I am printing thread id here
console_handler = StreamHandler()
console_handler.setFormatter(log_formatter)
log.addHandler(console_handler)
log.info("Hi, how are you")
Sample output from above:
2014-10-19 18:22:02,294 [INFO] root: Hi, how are you [140635865786176]