Given a string array of logs:
log = [
'[WARNING] 403 Forbidden: No token in request parameters',
'[ERROR] 500 Server Error: int is not subscription',
'[INFO] 200 OK: Login Successful',
'[INFO] 200 OK: User sent a message',
'[ERROR] 500 Server Error: int is not subscription'
]
I'm trying to get better with using dictionaries in python and want to loop through this array and print out something like this:
{'WARNING': {'403': {'Forbidden': {'No token in request parameters': 1}}},
'ERROR': {'500': {'Server Error': {'int is not subscriptable': 2}}},
'INFO': {'200': {'OK': {'Login Successful': 1, 'User sent a message': 1}}}}
Essentially, I want to return a dictionary with logging statistics formatted like above. I started writing out my method and wrote this so far:
def logInfo(logs):
dct = {}
for log in logs:
log = log.strip().split()
if log[2] == "Server":
log[2] = "Server Error:"
log.remove(log[3])
#print(log)
joined = " ".join(log[3:])
if log[0] not in dct:
log[0] = log[0].strip('[').strip(']')
dct[log[0]] = {}
if log[1] not in dct[log[0]]:
dct[log[0]][log[1]] = {}
if log[2] not in dct[log[0]][log[1]]:
dct[log[0]][log[1]][log[2]] = {}
if joined not in dct:
dct[log[0]][log[1]][log[2]][joined] = 1
else:
dct[log[0]][log[1]][log[2]][joined] += 1
else:
dct[joined].append(joined)
print(dct)
It prints this instead:
{'WARNING': {'403': {'Forbidden:': {'No token in request parameters': 1}}}, 'ERROR': {'500': {'Server Error:': {'int is not subscription': 1}}}, 'INFO': {'200': {'OK:': {'User sent a message': 1}}}}
The method itself is pretty long too, can anyone help and or maybe hint me to a more proficient way of handling this?