clean_logs.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import glob, re, os.path, textwrap
  2. from colorama import Fore, Back, Style
  3. def target_prefix(dir):
  4. if dir.startswith("net"):
  5. return "net"
  6. elif dir.startswith("serial"):
  7. return "serial"
  8. elif dir.startswith("util"):
  9. return "util"
  10. elif dir.startswith("runtime"):
  11. return "runtime"
  12. elif dir.startswith("zk"):
  13. return "zk"
  14. elif dir.startswith("raft"):
  15. return "raft"
  16. elif dir.startswith("sdk/src/crypto"):
  17. return "sdk::crypto"
  18. elif dir.startswith("sdk"):
  19. return "sdk"
  20. elif dir.startswith("contract/dao"):
  21. return "dao"
  22. elif dir.startswith("contract/money"):
  23. return "money"
  24. elif dir.startswith("rpc"):
  25. return "rpc"
  26. elif dir.startswith("system"):
  27. return "system"
  28. elif dir.startswith("dht"):
  29. return "dht"
  30. elif dir.startswith("consensus"):
  31. return "consensus"
  32. elif dir.startswith("zkas"):
  33. return "zkas"
  34. elif dir.startswith("blockchain"):
  35. return "blockchain"
  36. elif dir.startswith("wallet"):
  37. return "wallet"
  38. else:
  39. assert not dir or dir == "tx"
  40. return ""
  41. def target_suffix(prefix, base):
  42. if prefix in ("dao", "money"):
  43. # Just shorten the target to simply "dao" or "money"
  44. # We don't need the fine grained details
  45. return ""
  46. elif base in ("mod.rs", "lib.rs"):
  47. # Just use the module name as the target with these files
  48. return ""
  49. # Otherwise just use the filename as the target suffix
  50. return base.removesuffix(".rs")
  51. def log_target(fname):
  52. dir, base = os.path.dirname(fname), os.path.basename(fname)
  53. prefix = target_prefix(dir)
  54. suffix = target_suffix(prefix, base)
  55. # you don't need :: when the suffix is empty
  56. if not suffix and not prefix:
  57. return ""
  58. if not suffix:
  59. return prefix
  60. if not prefix:
  61. return suffix
  62. return f"{prefix}::{suffix}"
  63. def replace(fname, contents):
  64. target = log_target(fname)
  65. # You can debug like this:
  66. #if target != "consensus::proposal":
  67. # return ""
  68. print(f"Replacing {target}" + " "*(40 - len(target)) + f"[{fname}]")
  69. result = ""
  70. lines = contents.split("\n")
  71. i = 0
  72. while i < len(lines):
  73. line = lines[i]
  74. # Line number
  75. ln = lambda: i + 1
  76. # only used for debug output
  77. old_text = None
  78. new_text = None
  79. # This is used as a debug goto
  80. is_modified = False
  81. log_level = None
  82. if "trace!(" in line:
  83. log_level = "trace"
  84. elif "debug!(" in line:
  85. log_level = "debug"
  86. elif "info!(" in line:
  87. log_level = "info"
  88. elif "warn!(" in line:
  89. log_level = "warn"
  90. elif "error!(" in line:
  91. log_level = "error"
  92. if log_level is not None:
  93. # No target exists for this file at all. Just ignore these
  94. # We would normally delete any target set for these files
  95. # but so far we have none of them, so just ignore them.
  96. if not target:
  97. print(
  98. " "
  99. + Back.RED + "Skip [no target]:" + Style.RESET_ALL
  100. + f" {line}"
  101. )
  102. # Walk backwards to find the function name
  103. # Range is (i, 0]
  104. function_name = None
  105. for j in range(i - 1, -1, -1):
  106. past_line = lines[j]
  107. if (match := re.search(
  108. f"fn ([a-zA-Z0-9_]+)(<[a-zA-Z: +']+>)?\\(",
  109. past_line
  110. )):
  111. function_name = match.group(1)
  112. print(past_line, function_name)
  113. break
  114. assert function_name is not None
  115. if target in (
  116. "consensus::protocol_proposal",
  117. "consensus::protocol_sync",
  118. "consensus::protocol_sync_consensus",
  119. "consensus::protocol_tx",
  120. "runtime::db",
  121. "net::hosts",
  122. "net::protocol_address",
  123. "net::protocol_ping",
  124. "net::protocol_seed",
  125. "net::protocol_version",
  126. "net::p2p",
  127. ):
  128. target += f"::{function_name}()"
  129. # Single lines with a target that's a constant or string
  130. elif re.search(f'{log_level}!\\(target: ([A-Z_]+|"[a-zA-Z:_-]+"),', line):
  131. old_text = f"{ln()}: {line}"
  132. line = re.sub(
  133. 'target: ([A-Z_]+|"[a-zA-Z:_-]+"),',
  134. f'target: "{target}",',
  135. line
  136. )
  137. is_modified = True
  138. new_text = f"{ln()}: {line}"
  139. # Normal single lines with no target set
  140. elif f'{log_level}!("' in line:
  141. old_text = f"{ln()}: {line}"
  142. #print(f" No target: {line}")
  143. line = line.replace(f'{log_level}!(',
  144. f'{log_level}!(target: "{target}", ')
  145. is_modified = True
  146. new_text = f"{ln()}: {line}"
  147. # Multiline logs
  148. # We read the next line and check if there's a target set or not
  149. else:
  150. assert re.search(f"{log_level}!\\($", line)
  151. old_text = f"{ln()}: {line}"
  152. new_text = f"{ln()}: {line}"
  153. result += line + "\n"
  154. i += 1
  155. assert i < len(lines)
  156. line = lines[i]
  157. old_text += f"\n{ln()}: {line}"
  158. # Constants or target strings set
  159. if re.search('target: ([A-Z_]+|"[a-zA-Z:_-]+"),', line):
  160. line = re.sub(
  161. 'target: ([A-Z_]+|"[a-zA-Z:_-]+"),',
  162. f'target: "{target}",',
  163. line
  164. )
  165. new_text += f"\n{ln()}: {line}"
  166. # Multi-line logs with no target set
  167. # Insert an extra line with the target
  168. else:
  169. leading_space = lambda line: len(line) - len(line.lstrip())
  170. added_line = (" "*leading_space(line)
  171. + f'target: "{target}",')
  172. result += f"{added_line}\n"
  173. new_text += f"\n{ln()}: {added_line}\n{ln() + 1}: {line}"
  174. is_modified = True
  175. if is_modified:
  176. assert old_text is not None and new_text is not None
  177. print(
  178. Fore.RED
  179. + textwrap.indent(old_text, " < ")
  180. + Style.RESET_ALL
  181. )
  182. print(
  183. Fore.GREEN
  184. + textwrap.indent(new_text, " > ")
  185. + Style.RESET_ALL
  186. )
  187. print()
  188. result += f"{line}\n"
  189. i += 1
  190. return result
  191. def main():
  192. for fname in glob.glob("**/*.rs", root_dir="src/", recursive=True):
  193. with open(f"src/{fname}", "r") as f:
  194. contents = f.read()
  195. contents = replace(fname, contents)
  196. # Uncomment this to apply the changes
  197. #with open(f"src/{fname}", "w") as f:
  198. # f.write(contents)
  199. if __name__ == "__main__":
  200. main()