Skip to content

Instantly share code, notes, and snippets.

@bauergeorg
Created January 26, 2024 15:56
Show Gist options
  • Save bauergeorg/7d6b98d6aca6ea2c7bcdad922180c743 to your computer and use it in GitHub Desktop.
Save bauergeorg/7d6b98d6aca6ea2c7bcdad922180c743 to your computer and use it in GitHub Desktop.
Logging with progress bar
import logging
import time
from tqdm import tqdm
class TqdmHandler(logging.StreamHandler):
def __init__(self):
logging.StreamHandler.__init__(self)
def emit(self, record):
msg = self.format(record)
tqdm.write(msg)
if __name__ == "__main__":
log = logging.getLogger("myapp")
log.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# basic console logger: receives messages too
ch = TqdmHandler() # instead of: ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
log.addHandler(ch)
# additionally, log to file
logFileName = 'file.log'
fileLog = logging.FileHandler(logFileName, 'w', 'utf-8')
fileLog.setLevel(logging.INFO)
fileLog.setFormatter(formatter)
log.addHandler(fileLog)
log.info('Start')
for x in tqdm(range(10)):
log.info("Inside subtask: "+str(x))
time.sleep(.5)
log.info('Stop')
log.removeHandler(ch)
log.removeHandler(fileLog)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment