|
| 1 | +# ========================================================================= |
| 2 | +# This file is modified from https://github.com/SRT-Lab/ULP |
| 3 | +# |
| 4 | +# MIT License |
| 5 | +# Copyright (c) 2022 Universal Log Parser |
| 6 | +# |
| 7 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 8 | +# of this software and associated documentation files (the "Software"), to deal |
| 9 | +# in the Software without restriction, including without limitation the rights |
| 10 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 11 | +# copies of the Software, and to permit persons to whom the Software is |
| 12 | +# furnished to do so, subject to the following conditions: |
| 13 | +# |
| 14 | +# The above copyright notice and this permission notice shall be included in all |
| 15 | +# copies or substantial portions of the Software. |
| 16 | +# ========================================================================= |
| 17 | + |
| 18 | +import os |
| 19 | +import pandas as pd |
| 20 | +import regex as re |
| 21 | +import time |
| 22 | +import warnings |
| 23 | +from collections import Counter |
| 24 | +from string import punctuation |
| 25 | + |
| 26 | +warnings.filterwarnings("ignore") |
| 27 | + |
| 28 | + |
| 29 | +class LogParser: |
| 30 | + def __init__(self, log_format, indir="./", outdir="./result/", rex=[]): |
| 31 | + """ |
| 32 | + Attributes |
| 33 | + ---------- |
| 34 | + rex : regular expressions used in preprocessing (step1) |
| 35 | + path : the input path stores the input log file name |
| 36 | + logName : the name of the input file containing raw log messages |
| 37 | + savePath : the output path stores the file containing structured logs |
| 38 | + """ |
| 39 | + self.path = indir |
| 40 | + self.indir = indir |
| 41 | + self.outdir = outdir |
| 42 | + self.logName = None |
| 43 | + self.savePath = outdir |
| 44 | + self.df_log = None |
| 45 | + self.log_format = log_format |
| 46 | + self.rex = rex |
| 47 | + |
| 48 | + def tokenize(self): |
| 49 | + event_label = [] |
| 50 | + # print("\n============================Removing obvious dynamic variables======================\n\n") |
| 51 | + for idx, log in self.df_log["Content"].iteritems(): |
| 52 | + tokens = log.split() |
| 53 | + tokens = re.sub(r"\\", "", str(tokens)) |
| 54 | + tokens = re.sub(r"\'", "", str(tokens)) |
| 55 | + tokens = tokens.translate({ord(c): "" for c in "!@#$%^&*{}<>?\|`~"}) |
| 56 | + |
| 57 | + re_list = [ |
| 58 | + "([\da-fA-F]{2}:){5}[\da-fA-F]{2}", |
| 59 | + "\d{4}-\d{2}-\d{2}", |
| 60 | + "\d{4}\/\d{2}\/\d{2}", |
| 61 | + "[0-9]{2}:[0-9]{2}:[0-9]{2}(?:[.,][0-9]{3})?", |
| 62 | + "[0-9]{2}:[0-9]{2}:[0-9]{2}", |
| 63 | + "[0-9]{2}:[0-9]{2}", |
| 64 | + "0[xX][0-9a-fA-F]+", |
| 65 | + "([\(]?[0-9a-fA-F]*:){8,}[\)]?", |
| 66 | + "^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})(?:[ ][0-9]{2}:[0-9]{2}:[0-9]{2})?(?:[.,][0-9]{3})?", |
| 67 | + "(\/|)([a-zA-Z0-9-]+\.){2,}([a-zA-Z0-9-]+)?(:[a-zA-Z0-9-]+|)(:|)", |
| 68 | + ] |
| 69 | + |
| 70 | + pat = r"\b(?:{})\b".format("|".join(str(v) for v in re_list)) |
| 71 | + tokens = re.sub(pat, "<*>", str(tokens)) |
| 72 | + tokens = tokens.replace("=", " = ") |
| 73 | + tokens = tokens.replace(")", " ) ") |
| 74 | + tokens = tokens.replace("(", " ( ") |
| 75 | + tokens = tokens.replace("]", " ] ") |
| 76 | + tokens = tokens.replace("[", " [ ") |
| 77 | + event_label.append(str(tokens).lstrip().replace(",", " ")) |
| 78 | + |
| 79 | + self.df_log["event_label"] = event_label |
| 80 | + |
| 81 | + return 0 |
| 82 | + |
| 83 | + def getDynamicVars2(self, petit_group): |
| 84 | + petit_group["event_label"] = petit_group["event_label"].map( |
| 85 | + lambda x: " ".join(dict.fromkeys(x.split())) |
| 86 | + ) |
| 87 | + petit_group["event_label"] = petit_group["event_label"].map( |
| 88 | + lambda x: " ".join( |
| 89 | + filter(None, (word.strip(punctuation) for word in x.split())) |
| 90 | + ) |
| 91 | + ) |
| 92 | + |
| 93 | + lst = petit_group["event_label"].values.tolist() |
| 94 | + |
| 95 | + vec = [] |
| 96 | + big_lst = " ".join(v for v in lst) |
| 97 | + this_count = Counter(big_lst.split()) |
| 98 | + |
| 99 | + if this_count: |
| 100 | + max_val = max(this_count, key=this_count.get) |
| 101 | + for word in this_count: |
| 102 | + if this_count[word] < this_count[max_val]: |
| 103 | + vec.append(word) |
| 104 | + |
| 105 | + return vec |
| 106 | + |
| 107 | + def remove_word_with_special(self, sentence): |
| 108 | + sentence = sentence.translate( |
| 109 | + {ord(c): "" for c in "!@#$%^&*()[]{};:,/<>?\|`~-=+"} |
| 110 | + ) |
| 111 | + length = len(sentence.split()) |
| 112 | + |
| 113 | + finale = "" |
| 114 | + for word in sentence.split(): |
| 115 | + if ( |
| 116 | + not any(ch.isdigit() for ch in word) |
| 117 | + and not any(not c.isalnum() for c in word) |
| 118 | + and len(word) > 1 |
| 119 | + ): |
| 120 | + finale += word |
| 121 | + |
| 122 | + finale = finale + str(length) |
| 123 | + return finale |
| 124 | + |
| 125 | + def outputResult(self): |
| 126 | + self.df_log.to_csv( |
| 127 | + os.path.join(self.savePath, self.logName + "_structured.csv"), index=False |
| 128 | + ) |
| 129 | + |
| 130 | + def load_data(self): |
| 131 | + headers, regex = self.generate_logformat_regex(self.log_format) |
| 132 | + |
| 133 | + self.df_log = self.log_to_dataframe( |
| 134 | + os.path.join(self.path, self.logname), regex, headers, self.log_format |
| 135 | + ) |
| 136 | + |
| 137 | + def generate_logformat_regex(self, logformat): |
| 138 | + """Function to generate regular expression to split log messages""" |
| 139 | + headers = [] |
| 140 | + splitters = re.split(r"(<[^<>]+>)", logformat) |
| 141 | + regex = "" |
| 142 | + for k in range(len(splitters)): |
| 143 | + if k % 2 == 0: |
| 144 | + splitter = re.sub(" +", "\\\s+", splitters[k]) |
| 145 | + regex += splitter |
| 146 | + else: |
| 147 | + header = splitters[k].strip("<").strip(">") |
| 148 | + regex += "(?P<%s>.*?)" % header |
| 149 | + headers.append(header) |
| 150 | + regex = re.compile("^" + regex + "$") |
| 151 | + return headers, regex |
| 152 | + |
| 153 | + def log_to_dataframe(self, log_file, regex, headers, logformat): |
| 154 | + """Function to transform log file to dataframe""" |
| 155 | + log_messages = [] |
| 156 | + linecount = 0 |
| 157 | + with open(log_file, "r") as fin: |
| 158 | + for line in fin.readlines(): |
| 159 | + try: |
| 160 | + match = regex.search(line.strip()) |
| 161 | + message = [match.group(header) for header in headers] |
| 162 | + log_messages.append(message) |
| 163 | + linecount += 1 |
| 164 | + except Exception as e: |
| 165 | + print("[Warning] Skip line: " + line) |
| 166 | + logdf = pd.DataFrame(log_messages, columns=headers) |
| 167 | + logdf.insert(0, "LineId", None) |
| 168 | + logdf["LineId"] = [i + 1 for i in range(linecount)] |
| 169 | + return logdf |
| 170 | + |
| 171 | + def parse(self, logname): |
| 172 | + start_timeBig = time.time() |
| 173 | + print("Parsing file: " + os.path.join(self.path, logname)) |
| 174 | + |
| 175 | + self.logname = logname |
| 176 | + |
| 177 | + regex = [r"blk_-?\d+", r"(\d+\.){3}\d+(:\d+)?"] |
| 178 | + |
| 179 | + self.load_data() |
| 180 | + self.df_log = self.df_log.sample(n=2000) |
| 181 | + self.tokenize() |
| 182 | + self.df_log["EventId"] = self.df_log["event_label"].map( |
| 183 | + lambda x: self.remove_word_with_special(str(x)) |
| 184 | + ) |
| 185 | + groups = self.df_log.groupby("EventId") |
| 186 | + keys = groups.groups.keys() |
| 187 | + stock = pd.DataFrame() |
| 188 | + count = 0 |
| 189 | + |
| 190 | + re_list2 = ["[ ]{1,}[-]*[0-9]+[ ]{1,}", ' "\d+" '] |
| 191 | + |
| 192 | + generic_re = re.compile("|".join(re_list2)) |
| 193 | + |
| 194 | + for i in keys: |
| 195 | + l = [] |
| 196 | + slc = groups.get_group(i) |
| 197 | + |
| 198 | + template = slc["event_label"][0:1].to_list()[0] |
| 199 | + count += 1 |
| 200 | + if slc.size > 1: |
| 201 | + l = self.getDynamicVars2(slc.head(10)) |
| 202 | + pat = r"\b(?:{})\b".format("|".join(str(v) for v in l)) |
| 203 | + if len(l) > 0: |
| 204 | + template = template.lower() |
| 205 | + template = re.sub(pat, "<*>", template) |
| 206 | + |
| 207 | + template = re.sub(generic_re, " <*> ", template) |
| 208 | + slc["event_label"] = [template] * len(slc["event_label"].to_list()) |
| 209 | + |
| 210 | + stock = stock.append(slc) |
| 211 | + stock = stock.sort_index() |
| 212 | + |
| 213 | + self.df_log = stock |
| 214 | + |
| 215 | + self.df_log["EventTemplate"] = self.df_log["event_label"] |
| 216 | + if not os.path.exists(self.savePath): |
| 217 | + os.makedirs(self.savePath) |
| 218 | + self.df_log.to_csv( |
| 219 | + os.path.join(self.savePath, logname + "_structured.csv"), index=False |
| 220 | + ) |
| 221 | + elapsed_timeBig = time.time() - start_timeBig |
| 222 | + print(f"Parsing done in {elapsed_timeBig} sec") |
| 223 | + return 0 |
0 commit comments