How to use logger to print a list in just one line in Python

How to use logger to print a list in just one line in Python

You are using a for loop which iterates over all of your list and logs it one by one try: logger.info(Numbers in num_list are: {}.format( .join(map(str, num_list)))) to post them all in once

See: https://docs.python.org/3/library/stdtypes.html?highlight=str#str.join

There is a strong difference between an output stream (used by print) and a message log. The stream is a sequence of characters (or bytes for binary strings) that may happen to contain newline characters. Those newlines characters are then interpreted when you display them on a terminal (or when you print them).

A log is a sequence of messages, and each message is supposed to be atomic. Once a message has been logged, you cannot add anything to it but can only log new messages.

So you have to first fully build your message and then log it:

num_list = [1, 2, 3, 4, 5]
msg = Numbers in num_list are:  +  .join(num_list)      # fully build the message
logger.info(msg)                                            #  and then log it

How to use logger to print a list in just one line in Python

Not exactly what you want, but more lazy:
It may be usefull when you want to create some fast debug:

num_list = [1, 2, 3, 4, 5]
logger.info(str((Numbers in num_list are: ,num_list))

output:

(Numbers in num_list are: , [1, 2, 3, 4, 5])

Leave a Reply

Your email address will not be published.