Skip to content

Commit

Permalink
more logging improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
amancevice committed Jul 19, 2020
1 parent e8edfc5 commit 11074ad
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
23 changes: 23 additions & 0 deletions lambda_gateway/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import logging


def set_stream_logger(name, level=logging.DEBUG, format_string=None):
"""
Adapted from boto3.set_stream_logger()
"""
if format_string is None:
format_string = \
'%(addr)s - - [%(asctime)s] %(levelname)s - %(message)s'

logger = logging.getLogger(name)
handler = logging.StreamHandler()
formatter = logging.Formatter(format_string, '%-d/%b/%Y %H:%M:%S')
adapter = logging.LoggerAdapter(logger, dict(addr='::1'))
logger.setLevel(level)
handler.setLevel(level)
handler.setFormatter(formatter)
logger.addHandler(handler)
return adapter


logger = set_stream_logger(__name__)
10 changes: 5 additions & 5 deletions lambda_gateway/event_proxy.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import asyncio
import json
import os
import sys
from importlib.util import (spec_from_file_location, module_from_spec)

from lambda_gateway import lambda_context
from lambda_gateway import (lambda_context, logger)


class EventProxy:
Expand Down Expand Up @@ -35,6 +34,7 @@ def get_handler(self):

def invoke(self, event):
with lambda_context.start(self.timeout) as context:
logger.info('Invoking "%s"', self.handler)
return asyncio.run(self.invoke_async_with_timeout(event, context))

async def invoke_async(self, event, context=None):
Expand All @@ -49,8 +49,8 @@ async def invoke_async(self, event, context=None):

# Reject request if not starting at base path
if not path.startswith(self.base_path):
err = f'Rejected {path} -- Base path is {self.base_path}'
sys.stderr.write(f'{err}\n')
err = f'Rejected {path} :: Base path is {self.base_path}'
logger.error(err)
return self.jsonify(httpMethod, 403, message='Forbidden')

# Get & invoke Lambda handler
Expand All @@ -59,7 +59,7 @@ async def invoke_async(self, event, context=None):
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, handler, event, context)
except Exception as err:
sys.stderr.write(f'{err}\n')
logger.error(err)
message = 'Internal server error'
return self.jsonify(httpMethod, 502, message=message)

Expand Down

0 comments on commit 11074ad

Please sign in to comment.