I want to print a list using logging in only one line in Python 3.6. Currently my code looks like this.
logger = logging.getLogger()
logger.setLevel(log_level)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(log_level)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
# some codes in-between
num_list = [1, 2, 3, 4, 5]
logger.info("Numbers in num_list are: ")
for item in num_list:
logger.info(item)
What I want to get is
2018-07-23 17:29:30,200 - root - INFO - Numbers in num_list are: 1 2 3 4 5
However, I would get
2018-07-23 17:29:30,200 - root - INFO - Numbers in num_list are:
2018-07-23 17:29:30,200 - root - INFO - 1
2018-07-23 17:29:30,200 - root - INFO - 2
2018-07-23 17:29:30,200 - root - INFO - 3
2018-07-23 17:29:30,200 - root - INFO - 4
2018-07-23 17:29:30,200 - root - INFO - 5
I know if I used print
to output, I could have use print(item, end=" ")
to explicitly change what follows the output. However, it seems that the logging won't accept end
as an input parameter.
Does anyone have any ideas how I could get the desired output? Many thanks!
Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by comma use sep=”\n” or sep=”, ” respectively.
Python - Print Logs in a File. If you want to print python logs in a file rather than on the console then we can do so using the basicConfig() method by providing filename and filemode as parameter. The format of the message can be specified by using format parameter in basicConfig() method.
Modify print() method to print on the same line The print method takes an extra parameter end=” “ to keep the pointer on the same line. The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With