Logging
When an AI application runs, you need to know what it is doing, when something fails, and why it failed. Logging allows your Python application to record useful information while it runs.
Logging is a record of what your application is doing.
Instead of using print statements everywhere, Python's logging system lets you record messages with different levels such as INFO, WARNING, and ERROR.
What Is Logging?
Logging means recording events that happen while your program is running.
For example, an AI application might need to record:
- When the application starts
- Which API request was made
- How long an operation took
- When an error occurred
- When a file was processed
Application
↓
Event happens
↓
Logging system
↓
Log message
↓
Terminal / File / Monitoring system
print() vs Logging
Beginners often use print() to understand
what their application is doing.
print("Application started")
print("Calling AI API")
print("API request completed")
This works for very small programs, but it becomes difficult to manage in larger applications.
Logging gives you more control.
import logging
logging.info("Application started")
logging.info("Calling AI API")
logging.info("API request completed")
Logging allows you to control which messages should be displayed and how they should be stored.
Your First Log Message
Python has a built-in logging module.
You do not need to install anything.
import logging
logging.basicConfig(
level=logging.INFO
)
logging.info("Application started")
The INFO level tells Python that INFO
messages and more serious messages should be shown.
INFO:root:Application started
Logging Levels
Python provides several standard logging levels.
DEBUG ↓ Detailed information for developers INFO ↓ Normal application activity WARNING ↓ Something unexpected happened ERROR ↓ Something failed CRITICAL ↓ Very serious failure
Each level communicates a different level of importance.
DEBUG
DEBUG is used for detailed information that is useful while developing or troubleshooting an application.
import logging
logging.basicConfig(
level=logging.DEBUG
)
logging.debug("Starting API request")
logging.debug("Preparing request headers")
DEBUG messages are usually more detailed than normal application messages.
INFO
INFO is used for normal application activity.
import logging
logging.basicConfig(
level=logging.INFO
)
logging.info("Application started")
logging.info("File processing started")
logging.info("File processing completed")
This is one of the most commonly used logging levels in an application.
WARNING
WARNING indicates that something unexpected happened, but the application can still continue.
import logging
logging.basicConfig(
level=logging.INFO
)
user_limit = 90
if user_limit > 80:
logging.warning(
"User limit is getting high"
)
A warning does not necessarily mean that the application has failed.
ERROR
ERROR means something failed and needs attention.
import logging
logging.basicConfig(
level=logging.INFO
)
try:
result = 10 / 0
except ZeroDivisionError:
logging.error(
"Could not divide by zero"
)
The application can record the failure without relying only on a terminal print statement.
Logging Exceptions
For exceptions, logging.exception() is
particularly useful because it includes traceback
information.
import logging
logging.basicConfig(
level=logging.INFO
)
try:
result = 10 / 0
except Exception:
logging.exception(
"Something went wrong"
)
This gives developers much more information when debugging a real application.
Customize Log Messages
You can customize the format of your log messages.
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.info("Application started")
A log may look like:
2026-08-19 10:30:00 - INFO - Application started
Now the log contains the time, level, and message.
Save Logs to a File
Logs do not have to appear only in the terminal. You can save them to a file.
import logging
logging.basicConfig(
filename="app.log",
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.info("Application started")
logging.info("Processing document")
Python will write the messages into:
app.log
This becomes useful when you need to investigate what happened after an application has already run.
Creating a Logger
In larger applications, it is better to create a logger instead of using the root logger directly.
import logging
logger = logging.getLogger(__name__)
logger.info("Application started")
__name__ gives the logger the name of the
current Python module.
This becomes useful when your project contains multiple Python files.
Logging in Multiple Files
Imagine your AI application has:
ai-app/ │ ├── main.py ├── api_client.py ├── document_processor.py └── ai_service.py
Each file can create its own logger.
import logging
logger = logging.getLogger(__name__)
def process_document():
logger.info(
"Starting document processing"
)
This makes it easier to identify where a message came from.
Logging in an AI Application
Logging becomes particularly useful when an AI application performs several steps.
User uploads document
↓
Log upload
↓
Read document
↓
Log processing
↓
Create API request
↓
Log API request
↓
AI model processes request
↓
Log response
↓
Return result
For example:
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
logger.info("Application started")
logger.info("Document received")
logger.info("Sending request to AI API")
logger.info("AI response received")
logger.info("Application completed")
Never Log Secrets
This is critical when working with AI APIs.
Never do this:
logger.info(
f"API key: {api_key}"
)
You could expose the API key through log files, monitoring systems, or cloud logging services.
Instead:
logger.info(
"API key configured successfully"
)
Log useful information, not sensitive credentials.
Logging an API Request
Logging can help you understand how your API client behaves.
import logging
import requests
logger = logging.getLogger(__name__)
def get_products(url):
logger.info(
"Requesting products"
)
response = requests.get(
url,
timeout=10
)
response.raise_for_status()
logger.info(
"Products request completed"
)
return response.json()
Notice that we do not log sensitive headers or API keys.
A Simple AI Project Structure
ai-app/
│
├── main.py
├── api_client.py
├── document_processor.py
├── ai_service.py
│
└── logs/
└── app.log
The application code performs the work, while logging records what happened.
Mini Project — AI Application Logger
Create a small application that simulates processing a document with an AI service.
import logging
logging.basicConfig(
filename="app.log",
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def process_document(filename):
logger.info(
f"Processing document: {filename}"
)
try:
logger.info(
"Sending document to AI service"
)
# Simulate AI processing
result = "Document processed successfully"
logger.info(
"AI processing completed"
)
return result
except Exception:
logger.exception(
"Document processing failed"
)
return None
logger.info("Application started")
result = process_document(
"document.pdf"
)
if result:
logger.info(
"Application completed successfully"
)
This creates a basic application flow where important
events are recorded in app.log.
Good Logging Practices
- Use logging instead of many print statements in production applications.
- Use INFO for normal application activity.
- Use WARNING for unexpected but recoverable situations.
- Use ERROR for failures.
- Use DEBUG for detailed development information.
- Use logging.exception() when handling exceptions.
- Include useful context in messages.
- Never log passwords, API keys, or tokens.
- Store logs in files or a monitoring system when appropriate.
What You Learned
- What logging is
- Why logging is better than print() for larger applications
- Python's logging module
- DEBUG logging
- INFO logging
- WARNING logging
- ERROR logging
- Exception logging
- Custom log formats
- Saving logs to files
- Creating module-specific loggers
- Using logging in AI applications
- Why sensitive information should never be logged
If something goes wrong, your logs should help you understand why.
Logging gives your application a history of important events. Use INFO for normal activity, WARNING for unexpected situations, ERROR for failures, and DEBUG for detailed troubleshooting. Never put secrets such as API keys or passwords into your logs.