开发者

Python logger to dictionary [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago. 开发者_开发百科

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}"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜