How to use logger to print a list in just one line in Python
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
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
You can pass format strings and args to logging
.
The debug()
docs use this example:
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning('Protocol problem: %s', 'connection reset', extra=d)
For your case, you can can pass the num_list
to the format string as a string and it will pretty print it for you.
>>> num_list = [1, 2, 3, 4, 5, ]
>>> logger.info("Numbers in num_list are: %s", num_list)
INFO: Numbers in num_list are: [1, 2, 3, 4, 5]
>>> num_list = [1, 2, 3, 4, 5, [44,454,54], { "aa": 234} ]
>>> logger.info("Complex example: %s", num_list)
INFO: Complex example: [1, 2, 3, 4, 5, [44, 454, 54], {'aa': 234}]
As @Maico Timmerman pointed out:
It is better to let the logging module do the actual formatting using the %-syntax, since the message might not be printed at all.
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])