Created
January 26, 2024 15:56
-
-
Save bauergeorg/7d6b98d6aca6ea2c7bcdad922180c743 to your computer and use it in GitHub Desktop.
Logging with progress bar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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