【发布时间】:2019-09-23 15:59:23
【问题描述】:
我正在创建一个基于命令行样式脚本的日志解析器,该脚本打印出匹配项。这个想法是在日志中只输出与一些唯一值匹配的唯一行。下面是唯一拉取内容的示例格式。
From source books, query: ((domain:www.users.com || username:ed || location:boston || years:2 || title:lead || last_update:{2019-09-19T16:44:36.153Z TO 2019-09-19T16:48:04.125Z] && userid_17:*).
From source books, query: ((domain:www.users.com || username:john || location:austin || years:1 || title:associate || last_update:{2019-09-19T16:44:40.133Z TO 2019-09-19T16:48:06.145Z] && userid_18:*).
在其他行中,这些行的独特之处在于它们具有 userid_、域和年份。如果这 3 个不在行中,则不需要显示它们。
每 10 分钟将在日志中写入一个新行,并带有更新的 last_update 时间戳。我只需要该用户 ID 的第一次点击。在我的脚本中,我删除了 { ] 之间的时间戳,有效地使这些行都相同,以便更容易拉出唯一的行。
目前我的脚本正在“工作”,但我确信这可以清理并希望有想法。我在 Python 脚本方面还是很新的,所以批评家了。现在换行符不起作用,我觉得这会使这在视觉上更容易看到。
我也觉得 userid_ 作为唯一值会更好,但是不知道怎么说才能找到这个唯一值,但还必须有搜索 2 和 3。
标准:
- 唯一的输出,每个 id 应该只打印一个 userid_ 行
- 域和年份对于此搜索是唯一的,其他行包括 没有这两个匹配项的 userid_ 不需要打印
- 必须在每个独特的查找后有一个换行符,以便于阅读。
注意:这是一个带有其他命令行参数的工具。这是虚假数据,在此实时数据字符串中有更多项目,但截断以希望更容易理解请求。
import os, sys, argparse, urllib.parse, csv, re
parser = argparse.ArgumentParser(description='Choose an option')
# Setup required arguments
parser.add_argument('-b', action="store_true", help='searches users with domain and years')
args = parser.parse_args()
#Get Current Working Directory
dirpath = os.getcwd()
if args.b:
debug_log = dirpath+'/var/log/database/debug.log'
# 3 items are unique to this line vs other similar "userid_" lines
search1="userid_"
search2="domain"
search3="years"
with open(debug_log, 'r') as search:
unique = set()
for lines in search:
#search the file for matching terms
if search1 and search2 and search3 in lines:
#remove the last_update items, anything between { and ] to make it unique
removed = re.sub(r'\{(.*?)\]', '', lines)
if removed not in unique:
unique.add(removed)
print(unique)
这个脚本的输出如下所示,所以它确实有效。但是,即使输出中有 \n,换行符也不会。我假设是因为正在使用 set?当有 50 次以上的点击时,单行输出更难阅读。
{'From source books, query: ((domain:www.users.com || username:ed || location:boston || years:2 || title:lead || last_update: && userid_17:*).\n', 'From source books, query: ((domain:www.users.com || username:john || location:austin || years:1 || title:associate || last_update: && userid_18:*).\n'}
谢谢!
【问题讨论】:
标签: python file parsing unique