# HG changeset patch # User Anton Shestakov <engored@ya.ru> # Date 1501407106 0 # Node ID 7efa4ddd3e3e39925ffff372ad676ca19d9bfc53 � diff -r 000000000000 -r 7efa4ddd3e3e logger.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/logger.py Sun Jul 30 09:31:46 2017 +0000 @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +import json +import logging +from datetime import datetime +from os import makedirs +from os.path import abspath, dirname, join + +from tornado.ioloop import IOLoop +from tornado.options import define, options +from tornado.web import Application, HTTPError, RequestHandler + + +class LogHandler(RequestHandler): + def post(self): + try: + data = json.loads(self.request.body.decode('utf-8')) + except ValueError: + raise HTTPError(400, 'Malformed JSON') + self.log(data) + + def log(self, data): + logdir = abspath(join(dirname(__file__), 'log')) + makedirs(logdir, exist_ok=True) + time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ') + fn = join(logdir, time + '.json') + with open(fn, 'w') as f: + json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True) + + +class Logger(Application): + def __init__(self, debug=False): + handlers = [ + (r'.*', LogHandler) + ] + super().__init__(handlers, debug=debug) + + def listen(self, port, address='', **kwargs): + name = self.__class__.__name__ + logging.info('%s is serving on http://%s:%d/', name, address, port) + super().listen(port, address, **kwargs) + + +def main(): + define('listen', metavar='IP', default='127.0.0.1') + define('port', metavar='PORT', default=8111, type=int) + define('xheaders', metavar='True|False', default=False, type=bool) + define('debug', metavar='True|False', default=False, type=bool) + + options.parse_command_line() + + application = Logger(options.debug) + application.listen(options.port, options.listen, xheaders=options.xheaders) + + IOLoop.current().start() + + +if __name__ == '__main__': + main()