
PYTHON — Office Hours 11th August 2021 — Python
First, solve the problem. Then, write the code. — John Johnson

PYTHON — Exploring Data with Pandas in Python
The following is a brief tutorial on how to get started with logging in Python.
Python’s logging module is part of the standard library and provides features for event logging within applications. Here’s how to get started with logging in Python.
Getting Started with Logging in Python
Basic Configuration
The logging module provides a simple way to configure basic logging. Here’s an example of a basic configuration:
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')In this example, the basicConfig() method sets the logging level to DEBUG and specifies the format of the log messages.
Logging Messages
Once the basic configuration is set up, you can start logging messages. Here’s an example of how to log a message:
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')In this example, messages are logged using the debug(), info(), warning(), error(), and critical() methods, each corresponding to a different log level.
Logging to a File
You can also configure the logging module to write log messages to a file. Here’s an example of how to log messages to a file:
logging.basicConfig(filename='example.log', level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')In this example, the basicConfig() method specifies the filename for the log and sets the logging level and format as before.
Using Loggers
Loggers are used to customize the log messages according to the requirements of an application. Here’s an example of how to use loggers:
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
# Create a file handler
handler = logging.FileHandler('example.log')
# Create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# Add the handlers to the logger
logger.addHandler(handler)
# Log messages
logger.debug('This is a debug message')
logger.info('This is an info message')In this example, a custom logger is created with the name ‘my_logger’, and a file handler is added to it. The log messages are then customized and written to the file.
Conclusion
This tutorial covered the basics of getting started with logging in Python. The logging module provides a flexible and powerful way to incorporate logging into your Python applications. Whether it’s logging to the console or to a file, the logging module has you covered.







