Code 23: Logging

Learning Logs for Different Levels
coding
python
Author

Tony Phung

Published

February 10, 2025

1. Root Logger

Configure Root Logger that apples to whole app

  • Pros: Simple and quick & Less code
  • Cons: Lack of control & Limited customization
import logging

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
2025-02-10 13:12:50,256 - DEBUG - This is a debug message
2025-02-10 13:12:50,259 - INFO - This is an info message
2025-02-10 13:12:50,260 - WARNING - This is a warning message

2. Custom Logger Instance - To File

Pros:

  • Modular and organized
  • Granular control
  • Better for larger applications

Cons:
* More setup * Potential for inconsistency

import logging

# logger = logging.getLogger("my_app.module1") #create logger named my_app.module1
logger = logging.getLogger(__name__) 

logger.setLevel(logging.DEBUG)
print(logger.name)
file_handler = logging.FileHandler("app.log")
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(file_handler)
__main__

3. Log to Console As Well

console_handler = logging.StreamHandler()
console_formatter = logging.Formatter('%(levelname)s - %(message)s')  # Simple format for console
console_handler.setFormatter(console_formatter)
logger.addHandler(console_handler)
logger.debug("a debug msg going to file and console")
logger.info("an info msg to file and console")
DEBUG - a debug msg going to file and console
INFO - an info msg to file and console

4. Multiple Loggers and Hierarchy

import logging

logging.basicConfig(level=logging.DEBUG) # root logger

app_logger = logging.getLogger("my_app") # main app logger
app_logger.setLevel(logging.INFO)

module1_logger = logging.getLogger("my_app.module1")# specific module logger
module1_logger.setLevel(logging.DEBUG)

module2_logger = logging.getLogger("my_app.module2") # Logger for another module
module2_logger.setLevel(logging.WARNING)

app_logger.info("This is an info message from the main app") 
module1_logger.debug("This is a debug message from module 1")
module2_logger.warning("This is a warning message from module 2")