Python logger to dictionary [closed]
I am new in python...i am trying to read a python log file and make a dictionary. How will it be done with logger?
read a python log file and make a dictionary. How will it be done with logger?
It won't.
logging
writes logs.
file
reads logs.
What are you asking?
First, search for [Python] log parsing: https://stackoverflow.com/search?q=%5Bpython%5D+log+parsing
Second, please post some sample code.
As other commenter said, you don't want to use logging
to read the file, instead use file
. Here's an example of writing a log file, then reading it back.
#!/usr/bin/env python
# logger.py -- will write "time:debug:A:1" "time:debug:B:2" "time:debug:A:3" etc. log entries to a file
import logging, random
logging.basicConfig(filename='logfile.log',level=logging.DEBUG)
for i in range(1,100): logging.debug("%s:%d" % (random.choice(["a", "b"]), i))
# logfile.log now contains --
# 100.1:debug:A:1
# 100.5:debug:B:2
# 100.8:debug:B:3
# 101.3:debug:A:4
# ....
# 130.3:debug:B:100
#!/usr/bin/env/python
# reader.py -- will read aformentioned log files and sum up the keys
handle = file.open('logfile.log', 'r')
sums = {}
for line in handle.readlines():
time, debug, key, value = line.split(':')
if not key in sums: sums[key] = 0
sums[key] += value
print sums
# will output --
# "{'a': 50, 'b': 50}"
精彩评论