[go: up one dir, main page]

0% found this document useful (0 votes)
1 views2 pages

Logging

Uploaded by

myprojectai9
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)
1 views2 pages

Logging

Uploaded by

myprojectai9
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/ 2

o Open PyCharm and select New Project.

o Choose the Python interpreter (e.g., if using Python 3.5 or higher).

o Name your project, e.g., LogAnalyzerProject.

o Create a new Python file in the project (e.g., generate_logs.py).

generate_logs.py

import logging

# Configure logging to output to 'app.log'


logging.basicConfig(
filename='app.log', # Name of the log file
level=logging.DEBUG, # Log all levels (DEBUG and above)
format='%(asctime)s - %(levelname)s - %(message)s' # Log format
)

# Generate some simple log entries


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.")

log_analyzer.py

def analyze_logs(filepath):
level_counts = {"DEBUG": 0, "INFO": 0, "WARNING": 0, "ERROR": 0, "CRITICAL": 0}

# Open and read the log file


try:
with open(filepath, 'r') as log_file:
for line in log_file:
for level in level_counts:
# Use string formatting instead of f-strings
if " - {} - ".format(level) in line:
level_counts[level] += 1
break # Stop after finding the log level
except Exception as e:
print("Error reading log file:", e)
return level_counts

# Analyze the logs in 'app.log'


log_counts = analyze_logs("app.log")

# Display the log summary


print("Log Summary:")
for level, count in log_counts.items():
print("{}: {}".format(level, count))

You might also like