Logs the results of an attack to a file, or `stdout`.
| 14 | |
| 15 | |
| 16 | class FileLogger(Logger): |
| 17 | """Logs the results of an attack to a file, or `stdout`.""" |
| 18 | |
| 19 | def __init__(self, filename="", stdout=False, color_method="ansi"): |
| 20 | self.stdout = stdout |
| 21 | self.filename = filename |
| 22 | self.color_method = color_method |
| 23 | if stdout: |
| 24 | self.fout = sys.stdout |
| 25 | elif isinstance(filename, str): |
| 26 | directory = os.path.dirname(filename) |
| 27 | directory = directory if directory else "." |
| 28 | if not os.path.exists(directory): |
| 29 | os.makedirs(directory) |
| 30 | self.fout = open(filename, "w") |
| 31 | logger.info(f"Logging to text file at path {filename}") |
| 32 | else: |
| 33 | self.fout = filename |
| 34 | self.num_results = 0 |
| 35 | |
| 36 | def __getstate__(self): |
| 37 | # Temporarily save file handle b/c we can't copy it |
| 38 | state = {i: self.__dict__[i] for i in self.__dict__ if i != "fout"} |
| 39 | return state |
| 40 | |
| 41 | def __setstate__(self, state): |
| 42 | self.__dict__ = state |
| 43 | if self.stdout: |
| 44 | self.fout = sys.stdout |
| 45 | else: |
| 46 | self.fout = open(self.filename, "a") |
| 47 | |
| 48 | def log_attack_result(self, result): |
| 49 | self.num_results += 1 |
| 50 | # if self.stdout and sys.stdout.isatty(): |
| 51 | self.fout.write( |
| 52 | "-" * 45 + " Result " + str(self.num_results) + " " + "-" * 45 + "\n" |
| 53 | ) |
| 54 | self.fout.write(result.__str__(color_method=self.color_method)) |
| 55 | self.fout.write("\n") |
| 56 | |
| 57 | def log_summary_rows(self, rows, title, window_id): |
| 58 | if self.stdout: |
| 59 | table_rows = [[title, ""]] + rows |
| 60 | table = terminaltables.AsciiTable(table_rows) |
| 61 | self.fout.write(table.table) |
| 62 | else: |
| 63 | for row in rows: |
| 64 | self.fout.write(f"{row[0]} {row[1]}\n") |
| 65 | |
| 66 | def log_sep(self): |
| 67 | self.fout.write("-" * 90 + "\n") |
| 68 | |
| 69 | def flush(self): |
| 70 | self.fout.flush() |
| 71 | |
| 72 | def close(self): |
| 73 | self.fout.close() |
no outgoing calls
no test coverage detected