如何从日志行生成Python字典并累计ERROR计数、输出键值?
Absolutely doable! Here's a practical, Pythonic way to implement exactly what you're asking for:
Step-by-Step Breakdown
- Extract the process identifier from your log line (the
gnome-terminal-[12581]segment) - Initialize or update a dictionary to track error counts for each process
- Output the final dictionary in your requested format
Full Code Example
# Initialize an empty dictionary to hold error counts error_counts = {} # Your input log line log_line = "Aug 9 12:44:39 hostnameABC gnome-terminal-[12581]: Theme parsing error: gtk.css:6765:28: Missing opening bracket in color definition" # Extract the process name from the log line # Split the log by spaces, the 4th element (index 3) is our target process process_name = log_line.split()[3] # Update the error count dictionary if process_name in error_counts: # If the process already exists, increment the ERROR count error_counts[process_name]["ERROR"] += 1 else: # If it's a new process, set initial ERROR count to 1 error_counts[process_name] = {"ERROR": 1} # Output the results as requested print("字典名称: error_counts") for proc, count_data in error_counts.items(): print(f"{proc} = {count_data}")
Handling Multiple Log Lines
If you have a batch of log lines to process, wrap the logic in a loop for efficiency:
error_counts = {} log_lines = [ "Aug 9 12:44:39 hostnameABC gnome-terminal-[12581]: Theme parsing error: gtk.css:6765:28: Missing opening bracket in color definition", "Aug 9 12:45:10 hostnameABC gnome-terminal-[12581]: Another theme parsing error", "Aug 9 12:46:02 hostnameABC firefox-[9876]: Network error: Connection timed out" ] for line in log_lines: process_name = line.split()[3] if process_name in error_counts: error_counts[process_name]["ERROR"] += 1 else: error_counts[process_name] = {"ERROR": 1} # Print the final counts print("字典名称: error_counts") for proc, count_data in error_counts.items(): print(f"{proc} = {count_data}")
Sample Output for the Batch Processing Example:
字典名称: error_counts gnome-terminal-[12581] = {'ERROR': 2} firefox-[9876] = {'ERROR': 1}
内容的提问来源于stack exchange,提问作者user3826395
相关产品推荐
相关产品推荐

