Skip to content

Instantly share code, notes, and snippets.

@joelhsmith
Last active May 20, 2019 20:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelhsmith/c36ad701d5d9beb598962dc62cc3d2df to your computer and use it in GitHub Desktop.
Save joelhsmith/c36ad701d5d9beb598962dc62cc3d2df to your computer and use it in GitHub Desktop.
Convert Lighthouse 4 JSON audit file to a common log format and append the results to it each time it runs
import json
import argparse
import io
import sys
def get_args():
example_text = '''
examples:
python3 ./logify.py --input-file='foo.json'
lighthouse https://cats.com --only-categories=accessibility --output='json' | python3 ./logify.py --input-file='-' >> logified-lighthouse.log
'''
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input-file', help='Path to your JSON file. To specify stdin, use a dash "-" or omit argument.', default="-")
return parser.parse_args()
def filter_audits(x, data, keepers):
""" Return only audits with metrics """
if data['audits'][x]['scoreDisplayMode'] == 'error':
keepers['audit__' + x] = 0
elif data['audits'][x]['scoreDisplayMode'] == 'notApplicable':
keepers['audit__' + x] = 1
elif data['audits'][x]['scoreDisplayMode'] != ('manual' or 'informative'):
keepers['audit__' + x] = data['audits'][x]['score']
return keepers
def convert_to_log(data):
""" Convert JSON to log freindly format """
dataToLog = data['fetchTime'] + ' '
interesting_keys = ['lighthouseVersion', 'requestedUrl', 'finalUrl']
keepers = {x: data[x] for x in interesting_keys if x in data}
for x in data['categories']:
keepers['total__' + x + '_score'] = data['categories'][x]['score']
for x in data['audits']:
filter_audits(x, data, keepers)
for key, value in keepers.items():
key = key.replace('-','_')
dataToLog += '%s=%s' % (key, repr(value) + ' ')
return dataToLog
def read_input(input_file):
""" Read Lighthouse JSON file """
if type(input_file) is str:
with io.open(input_file, encoding='utf-8') as stream:
return json.JSONDecoder().decode(stream.read())
else:
return json.JSONDecoder().decode(input_file.read())
def main():
""" Get data and print log """
args = get_args()
if args.input_file == '-':
data = json.load(sys.stdin, encoding='utf-8')
else:
data = read_input(args.input_file)
print(convert_to_log(data))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment