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

18,968

Solution 1

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

Solution 2

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

Solution 3

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])

Solution 4

Another nice short way I've found here -

nums = [3, 87, 28, 25, 96]
logging.debug("Here are my favourite numbers: " + str(nums)[1:-1])

"""
 Output:
 Here are my favorite numbers: 3, 87, 28, 25, 96
""" 

One more using map -

logging.debug("Favourite numbers are: ".join(map(str, nums))
Share:
18,968

Related videos on Youtube

Jekyll SONG
Author by

Jekyll SONG

Updated on March 29, 2022

Comments

  • Jekyll SONG
    Jekyll SONG about 2 years

    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!

    • kabanus
      kabanus almost 6 years
      Why aren't you passing the list? as in logger.info(num_list)?
  • Jekyll SONG
    Jekyll SONG almost 6 years
    Thanks for the insightful comments. I guess the lesson here is that I try too hard on finding the connection between logging and print to forget that I could actually concatenate the string before output it. I have been trying to change the logging.config but ignore the simpler way
  • Maico Timmerman
    Maico Timmerman about 3 years
    It is better to let the logging module do the actual formatting using the %-syntax, since the message might not be printed at all.
  • idbrii
    idbrii about 2 years
    This deferred execution is a neat idea. The implementation could be very simple but still recursive by using pprint.pformat(self._seq) to build the string. pprint is part of the standard library. However, it looks like logging already supports deferred formatting.
  • idbrii
    idbrii about 2 years
    I guess this would be a good solution if you wanted to customize how to print the data (non default args to pformat).
  • idbrii
    idbrii about 2 years
    @MaicoTimmerman: Is using %s like in my answer what you're referring to?
  • gladd
    gladd almost 2 years
    @idbrii Gads! I don't know how I missed that Python has supported the string formatting operator for ages. I must have been thinking Java6 when I wrote it. Been away from Python for a while :-S
  • gladd
    gladd almost 2 years
    Thanks for the kind words of support re customising @idbrii, however it was me just being dufus!