从日志文件中提取某些数据

Pull certain data from log file

我正在创建一个程序,该程序将根据用户每天访问网站的次数对 IP 地址进行排序。我将从 apache 日志文件中获取我的数据。This is the example I'll learn from

有没有我可以使用的库或内置函数,以便仅从日志中附加 IP 地址和日期?

我在网上搜索过这方面的信息,但是,如果有任何看起来有用的文档,我会非常感兴趣地阅读它!

我试过创建一个列表,我将每一行附加到其中。我的问题是我正在寻找一种更好的方法来执行此操作,而不是附加整行,只附加 IP 地址和日期。

with open(log_file) as f:
    for line in f:
        IP, date = line.partition("]")[0].split(" - - [")

给定示例日志文件,如果每个新行都以 IP 开头,那么就足够了。你如何存储它取决于你。

在我看来,ip列在第一位。这意味着您可以逐行读取文件,去掉第一个单词,即 ip,并将其附加到要返回的列表中。如果你想做更多的事情 searching/filtering,我建议通过读取和写入日志文件来格式化日志,格式为 xml 或 json 类型的格式。它比字符串块更容易搜索。

 def append_log_storage(file, storage_file):
    root_elm = ET.Element('root')  
    # Load file to memory
    log_content = None
    with open(file) as f:
        log_content = f.readlines()
    f.close()
    # Write to file    
    f = open(file, 'w')
    for line in log_content:
        if line == '\n':
            continue 
        ip = line.partition(' ')[0]
        ip_log_elm = ET.SubElement(root_elm, 'log')
        ip_elm = ET.SubElement(ip_log_elm, 'ip')  
        # date_elm, etc. Add any other data for the log element
        ip_elm.text = ip  
    f.close()
    xml_data = ET.tostring(root_elm)
    xml_file = open(storage_file, 'wb')
    xml_file.write(xml_data)

def read_log_details(file):
    # Read file by line
    ip_list = []
    with open(file) as f:
        for line in f:
            if line == '\n':
                continue 
            ip = line.partition(' ')[0]
            ip_list.append(ip)
    f.close()
    return ip_list

read_log_details('log.txt')
#append_log_storage('log.txt', 'log.xml')

https://stackabuse.com/reading-and-writing-xml-files-in-python/