#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Парсер логов Apache2
Запуск: apache_log_parser.py /var/log/apache2/other_vhosts_access.log
© Falcon Elsystem 2021
"""

import sys

def dictify_logline(line):
    split_line = line.split()
    if len(split_line) < 10 or split_line[10] == '"-"':
        return False
    else:
        return {'remote_host': split_line[1],
            'bytes_send': split_line[10],
        }

def generate_log_report(logfile):
    report_dict = {}
    for line in logfile:
        line_dict = dictify_logline(line)
        if not line_dict == False:
            try:
                bytes_send = int(line_dict['bytes_send'])
            except ValueError:
                continue
            report_dict.setdefault(line_dict['remote_host'],[]).append(bytes_send)
        else:
            continue
    return report_dict

if __name__ == "__main__":
    if not len(sys.argv) > 1:
        print('\nУкажите файл логов Apache2')
        print(__doc__)
        sys.exit(1)
    infile_name = sys.argv[1]
    try:
        infile = open(infile_name, 'r')
    except IOError:
        print(__doc__)
        sys.exit(1)
    log_report = generate_log_report(infile)
    print(log_report)
    infile.close()

