Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
logging vs print
#1
I'm learning to use logging in every project but, I'm starting to question the difference between logging.info vs print() they seem to have the same use. I've read the official documentation at https://docs.python.org/3/howto/logging....d-tutorial. but I still don't understand the difference. can anyone explain the difference with a real example?

I have a simple example of why I'm confused by the two functions:
import logging
import random


module_logger = logging.getLogger(__name__)

ms_handler = logging.FileHandler("test_logging.log", mode="w")
ms_handler.setLevel(logging.WARNING)

ms_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
ms_handler.setFormatter(ms_format)

module_logger.addHandler(ms_handler)

def rand_num():
	return random.randint(1, 10)

def user_input(ipt):
	user = int(input("> "))
	while user != ipt:
		print("wrong number!")
		module_logger.warning("wrong number!")
		user = int(input("> "))

	return user

def play():
	user_input()

play()
what I see the difference is that logging can log to a file or SMTP or something and have a format to make it clear what's going on in the code.
Reply
#2
After you set up logging in the places you want it, you can control it globally. If you have prints in different places and want to modify them, you have to edit every line to change their behavior.

You can leave debug logging in your code and keep it quiet most of the time, but turn it on when you're trying to find a problem. You can have all the logging go to a different file by changing one line.

If you have a 12 line script, it's easier to throw in a print statement to help debug something than set up logging (but lots of people would).
If you have 5000 lines of code in several modules, you don't want to be fiddling with print statements everywhere (and maybe forget to take some out because the code path isn't run very often and you didn't notice that you left some debugging lines active).

Standard logging formats give you discipline to put useful information in every time. I've been annoyed with production code that generated some logs, but had no indication of what module generated it, or timestamp. If they'd used standard log formatting, all that information would have been there.
Gribouillis and syafiq14 like this post
Reply
#3
(Aug-28-2021, 04:26 AM)syafiq14 Wrote: but I still don't understand the difference. can anyone explain the difference with a real example?
Good logging practice Wrote:Logging is important in our life.
When you transfer money, there will be logs for the transaction.
When an airplane is flying, the black box will record flight data.
If something goes wrong, people can read the log and get a chance to figure out what happened.
Likewise, logging is also essential for software development.
When a program crashes, if there is no logging record, you have little chance to understand what happened.
Personal many years ago i had a bigger project which had GUI interface and did interactive with web/parsing stuff and several 3 party program.
I had no logging and people send me like 50 lines error message when GUI crash.
Because i had no logging i had to ask them what they did do to get that error message,this is not ideal at all.

Loguru is more enjoyable and it has little boilerplate,and in general much more straight forward to use.
I never use logging in standard library anymore.
Example:
from loguru import logger

logger.remove() # Only info to file
logger.add("file.log", rotation="2 day")

@logger.catch
def user_input(ipt):
    user = int(input("> "))
    logger.info(user)
    while user != ipt:
        print("wrong number!")
        logger.info("wrong number!")
        user = int(input("> "))
        logger.info(user)
    return user

def play():
    user_input(99)

play()
So now also catch Exception(as any string input will break it),just bye adding the decorator.

Output:
2021-08-28 12:20:08.831 | INFO | __main__:user_input:9 - 4 2021-08-28 12:20:08.834 | INFO | __main__:user_input:12 - wrong number! 2021-08-28 12:20:10.543 | INFO | __main__:user_input:14 - 55 2021-08-28 12:20:10.544 | INFO | __main__:user_input:12 - wrong number! 2021-08-28 12:20:12.331 | INFO | __main__:user_input:14 - 100 2021-08-28 12:20:12.332 | INFO | __main__:user_input:12 - wrong number! 2021-08-28 12:20:15.265 | ERROR | __main__:play:18 - An error has been caught in function 'play', process 'MainProcess' (7584), thread 'MainThread' (30520): Traceback (most recent call last): File "G:\div_code\loogg.py", line 20, in <module> play() -> <function play at 0x000001B044E2C160> > File "G:\div_code\loogg.py", line 18, in play user_input(99) -> <function user_input at 0x000001B044E0E790> File "G:\div_code\loogg.py", line 13, in user_input user = int(input("> ")) ValueError: invalid literal for int() with base 10: 'car'
syafiq14 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  logging messages ahead of print messages vindo 6 3,214 Jun-18-2019, 02:45 PM
Last Post: vindo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020