0% found this document useful (0 votes)
10 views9 pages

Log

Uploaded by

bishesh.shahi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views9 pages

Log

Uploaded by

bishesh.shahi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

CS 466 – Secure Software Development

By Dr. Daniel Nash, MS, CISSP

Student Name: Bishesh Shahi (____/20)


Instructions: Let's craft a Python script to demonstrate log writing:
Python
import logging

# Configure the logger


logging.basicConfig()

# Write log messages


logging.debug('CS 466 homework script')

try:
# Perform some homework calculations
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
logging.xxx('appropriate message', exc_info=False)

logging.info('Homework script completed')

Explanation:
1. Import: create and import the logging module by a file to work with
logs.
2. Configuration:
o basicConfig sets up a basic logger.
o filename specifies the log file name.
o level sets the minimum log level to record (DEBUG in this case).
o format defines the structure of log messages.
3. Logging:
o We use logging.debug to record the start of the script.

o A try-except block handles potential errors.


o In case of an error, logging.error logs the message along with the
exception details (exc_info=True).
o Finally, logging.info records the completion of the script.
How to use:
1. Save this code as a Python file (e.g., homework.py).
2. Modify the code to add:
1. Use .basicConfig() – add the appropriate items to:
1. Create and get a config file that has your appropriate
formatting (ini file)
2. Filename to specify the log file name. Append to a file your
logs (optionally – you can write to the sysout and log) (from
ini file)
3. Set the logging level to DEBUG (from ini file)
4. Format to define the structure the log message (from ini
file)
2. Set the appropriate logging level for the exception
3. Create a meaningful message for the exception and exec_info
set to capture a trace back
3. Run the script.
4. Check the my_homework.log file to see the logged messages.
Important considerations:
 Log Levels:
Choose the appropriate log level ( DEBUG, INFO, WARNING, ERROR, CRITICAL)
based on the severity of the message.
 Formatting:
Customize the log format to include relevant information like
timestamps, module names, and line numbers.
 Structured Logging:
Consider using structured logging (e.g., JSON format) for easier analysis.
 Log Rotation:
Consider rotating log files to prevent them from growing too large.
Discuss log rotation options, including log retention and size/time for
different log levels.
Deliverables (uploaded to test and copied to this document to turn in):

1. Modified homework.py file with all the required updates.(____/5)

a. Screenshot of the code running


2. Your ini file (____/4)
3. Your log file with the output (____/3)

4. Answer Questions:
a. Explain each log level ( DEBUG, INFO, WARNING, ERROR, CRITICAL)
and recommend retention for each. (____/2)

DEBUG (Retention: 1-7 days)

 Most detailed information


 Used for troubleshooting
 Contains sensitive data that should be cleared frequently
 Example: Variable values, function entry/exit points

INFO (Retention: 30 days)

 General operational events


 Application lifecycle events
 User actions and system state changes
 Example: Application startup/shutdown, user login
WARNING (Retention: 90 days)

 Indicate potential issues that don't prevent operation


 Used for deprecated features or unusual behavior
 Example: High resource usage, approaching limits

ERROR (Retention: 180 days)

 Errors that prevent specific operations but don't crash


application
 Need investigation but allow continued operation
 Example: Failed user actions, API errors

CRITICAL (Retention: 365 days)

 Severe errors that prevent application from functioning


 Require immediate attention
 Example: Database connection failure, system crash

b. Explain the proper formatting of logs with recommendations


for each log level (____/2)

 For All levels: %


(asctime)s - %(levelname)s - %(name)s - [%(process)d] - %
(pathname)s:%(lineno)d - %(message)s

 DEBUG: Include thread ID, function name


%(asctime)s - %(levelname)s - %(threadName)s - %
(funcName)s - %(message)s

 INFO: Include module and basic context


%(asctime)s - %(levelname)s - %(module)s - %(message)s

 WARNING/ERROR/CRITICAL: Include full context and stack trace


%(asctime)s - %(levelname)s - %(name)s - %(pathname)s:%
(lineno)d - %(message)s
Exception: %(exc_info)s

c. Explain why logging is important and a better option than


print statement (____/2)

Configurability:

 Can enable/disable different log levels without code changes


 Can route output to multiple destinations (file, console,
network)
 Can format output consistently across application

Performance:

 Logging can be disabled for production without removing code


 Better memory management with log rotation
 Asynchronous logging options available

Context:

 Automatically includes timestamps and other metadata


 Can include stack traces and error context
 Hierarchical logging with different levels

Production Ready:

 Built-in support for log rotation and archiving


 Thread-safe logging
 Can handle concurrent writes from multiple processes

d. What is the default log level and filename write mode used by
Python logging? (____/2)

Default Log Level: WARNING

 Only WARNING, ERROR, and CRITICAL messages are displayed by


default
 This helps reduce noise in production environments

Default Filename Write Mode: 'a' (append)

 New log entries are added to the end of existing log files
 Preserves historical log data across application restarts
References

• 10 Best Practices for Logging in Python


• 8 Python Logging Pitfalls to Avoid
• A Comprehensive Guide to Logging in Python
• Analyzing and Troubleshooting Python Logs
• Comprehensive Guide to Python Logging in the real world Part 1
• Crafting Your Custom Logger in Python: A Step-by-Step Guide
• How to set up Logging for Python Projects
• How to Write to a File Using the Logging Python Module - A Step-by-
Step Guide
• Log File Analysis
• logging — Logging facility for Python
• Logging Cheat Sheet
• Logging Cookbook
• Logging in Python: A Comparison of the Top 6 Libraries
• logging.config — Logging configuration
• Mastering the Art of Logging in Python: A Complete Guide
• Python logging
• Python Logging - From Setup to Monitoring with Best Practices
• Python Logging – Simplest Guide with Full Code and Examples
• Python logging formats: How to collect and centralize Python logs
• Python Logging Tutorial: How-To, Basic Examples & Best Practices
• The hitchhiker’s guide to Python Logging
• What is the best string formatting technique for logging in Python?

Video
• Modern Python Logging (Video)
• Python Logging: How to Write Logs Like a Pro! (video)
• Python Tutorial: Logging Basics - Logging to Files, Setting Levels, and
Formatting (video)

You might also like