Using Logging correctly in python

Advertisements

My code looks like this. It is for image reshuffling in a couple of folders. Please assume that I have made all the required imports correctly.

logging.basicConfig(filename = 'make_folders.log',  filemode= 'w', level=logging.INFO, format='%(asctime)::%(message)s')




def get_path_list(directory: str) -> list:
    """
    Get a list of absolute paths of all the files in the directory.

    :param directory: Path to the directory from which the file paths are to be extracted.

    """
    path_list =[]

    for file in glob.glob(pathname=directory+'/*.png', recursive=True):
        path_list.append(file)

    return path_list


# Make a list of all the images contained in folder A and folder B
img_A = get_path_list(args.source_A)
img_B = get_path_list(args.source_B)

try:
    assert len(img_A) == len(img_B)

except AssertionError:
    logging.error("The number of images in source_A folder and source_B folder are not the same. Check input folders.")

# Find how many images we want in training, validation and test sets based on the length of list containing all image paths.
train_len = round(0.7 * len(img_A))
val_len = round(0.15 * len(img_A))
test_len = val_len

logging.info("Total number of training, validation and test images in destination folder A and B are {}, {} and {} respectively".format(train_len, val_len, test_len))

I am getting following error while using logging.info()

logging.info("Total number of training, validation and test images in destination folder A and B are {}, {} and {} respectively".format(train_len, val_len, test_len))
Message: 'Total number of training, validation and test images in destination folder A and B are 5265, 1128 and 1128 respectively'
Arguments: ()

can someone please tell me what am I doing wrong?

>Solution :

Your error comes from:

format='%(asctime)::%(message)s'

Change it to:

format='%(asctime)s %(message)s'

And it works.

Additionally, newer versions of Python suggest we use f-strings instead of string formatting:

logging.info(f"Total number of training, validation and test images in destination folder A and B are {train_len}, {val_len} and {test_len} respectively")

Leave a ReplyCancel reply