Advertisement
Thewest123

format_logs

Apr 4th, 2023 (edited)
586
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.55 KB | None | 0 0
  1. """
  2. This script formats a log file of thread messages into a table.
  3.  
  4. Usage:
  5.    python format_logs.py <log_file.txt>
  6.  
  7. Example:
  8.    log_file.txt containing messages in format '[threadName](space)message':
  9.        [0] Start
  10.        [1] I am from thread one
  11.        [2] I am from thread two
  12.        [2] I am also two
  13.        [3] Three!
  14.        [1] Lorem
  15.        [1] Ipsum
  16.        [1] Dolor
  17.        [3] Some
  18.        [2] Another message
  19.        [1] Delivered
  20.        [0] End
  21.    
  22.    $ python format_logs.py log_file.txt
  23.        +----+-------+----------------------+----------------------+--------+
  24.        | #  | [0]   | [1]                  | [2]                  | [3]    |
  25.        +----+-------+----------------------+----------------------+--------+
  26.        | 1  | Start |                      |                      |        |
  27.        | 2  |       | I am from thread one |                      |        |
  28.        | 3  |       |                      | I am from thread two |        |
  29.        | 4  |       |                      | I am also two        |        |
  30.        | 5  |       |                      |                      | Three! |
  31.        | 6  |       | Lorem                |                      |        |
  32.        | 7  |       | Ipsum                |                      |        |
  33.        | 8  |       | Dolor                |                      |        |
  34.        | 9  |       |                      |                      | Some   |
  35.        | 10 |       |                      | Another message      |        |
  36.        | 11 |       | Delivered            |                      |        |
  37.        | 12 | End   |                      |                      |        |
  38.        +----+-------+----------------------+----------------------+--------+
  39. """
  40.  
  41. import sys
  42. import re
  43.  
  44. if len(sys.argv) == 1:
  45.     print(f"Usage: python {sys.argv[0]} <log_file.txt>\n")
  46.     sys.exit()
  47.  
  48. log_file_path = sys.argv[1]
  49. try:
  50.     with open(log_file_path, 'r') as f:
  51.         input_logs = f.read()
  52. except FileNotFoundError:
  53.     print(f"Error: File '{log_file_path}' not found")
  54.     sys.exit()
  55.  
  56. # extract thread names and messages from input logs
  57. logs = []
  58. for line in input_logs.split("\n"):
  59.     match = re.match(r"(\[.+\])\s(.+)", line)
  60.     if match:
  61.         logs.append({
  62.             "thread": match.group(1),
  63.             "message": match.group(2)
  64.         })
  65.  
  66. # create a list of dictionaries to represent the table
  67. table = []
  68. for i, log in enumerate(logs):
  69.     row = {"#": i+1, log["thread"]: log["message"]}
  70.     for log2 in logs[i+1:]:
  71.         if log2["thread"] not in row:
  72.             row[log2["thread"]] = ""
  73.     table.append(row)
  74.  
  75. # find maximum message length for each column
  76. max_lengths = {key: len(key) for key in table[0].keys()}
  77. for row in table:
  78.     for key, value in row.items():
  79.         max_lengths[key] = max(max_lengths[key], len(str(value)))
  80.  
  81. # print the table header
  82. row_str = "| {:<{}} |".format("#", max_lengths["#"])
  83. for key, value in max_lengths.items():
  84.     if key != "#":
  85.         row_str += " {:<{}} |".format(key, value)
  86.  
  87. separator = "+" + "-" * (max_lengths["#"]+2)
  88. for key, value in max_lengths.items():
  89.     if key != "#":
  90.         separator += "+" + "-" * (value+2)
  91.  
  92. print(separator + "+")
  93. print(row_str)
  94. print(separator + "+")
  95.  
  96. # print the table rows
  97. for row in table:
  98.     row_str = "| {:<{}} |".format(row["#"], max_lengths["#"])
  99.     for key, value in max_lengths.items():
  100.         if key != "#":
  101.             row_str += " {:<{}} |".format(row.get(key, ""), value)
  102.     print(row_str)
  103. print(separator + "+")
  104.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement