summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLars Wirzenius <liw@liw.fi>2017-08-04 16:40:20 +0300
committerLars Wirzenius <liw@liw.fi>2017-08-04 16:40:20 +0300
commit4b438adf30380d8cee7c17319e46ffebb4b0385f (patch)
treec38b08149b42b56db025347dbadbd5b6cc3d84bd
parent51f5ef48b57db80f082f939401dfb8eed61dd864 (diff)
downloadapifw-4b438adf30380d8cee7c17319e46ffebb4b0385f.tar.gz
Add: way to set log context in API
-rw-r--r--NEWS1
-rw-r--r--apifw/bottleapp.py13
-rw-r--r--apifw/http.py6
3 files changed, 20 insertions, 0 deletions
diff --git a/NEWS b/NEWS
index 78c8283..e24aab6 100644
--- a/NEWS
+++ b/NEWS
@@ -7,6 +7,7 @@ This file summarizes changes between releases of `apifw`.
Version 0.5+git, not yet released
---------------------------------
+* Add a way to set the log (slog) context via the API class.
Version 0.5, released 2017-08-03
---------------------------------
diff --git a/apifw/bottleapp.py b/apifw/bottleapp.py
index b248858..1b6f6b9 100644
--- a/apifw/bottleapp.py
+++ b/apifw/bottleapp.py
@@ -36,6 +36,18 @@ class BottleLoggingPlugin(apifw.HttpTransaction):
# the HTTP request and response, and to amend the response by
# adding a Date header.
+ def __init__(self):
+ super().__init__()
+ self._context_setter = None
+
+ def set_log_context_setter(self, context_setter):
+ self._context_setter = context_setter
+
+ def set_log_context(self):
+ if self._context_setter is not None:
+ return self._context_setter()
+ return None
+
def apply(self, callback, route):
def wrapper(*args, **kwargs):
@@ -216,6 +228,7 @@ def create_bottle_application(api, logger, config):
app = BottleApplication(bottleapp, api)
plugin = BottleLoggingPlugin()
+ plugin.set_log_context_setter(api.get_log_context)
if logger:
plugin.set_dict_logger(logger)
app.add_plugin(plugin)
diff --git a/apifw/http.py b/apifw/http.py
index 6b6a1e2..2b2855f 100644
--- a/apifw/http.py
+++ b/apifw/http.py
@@ -86,12 +86,18 @@ class HttpTransaction:
log.update(d)
return log
+ def set_log_context(self, contex):
+ # This can be overridden by subclasses.
+ pass
+
def perform_transaction(self, callback, *args, **kwargs):
try:
+ old_context = self.set_log_context()
self._log_request()
data = callback(*args, **kwargs)
self.amend_response()
self._log_response()
+ self.set_logcontext(old_context)
return data
except SystemExit:
# If we're exiting, we exit. No need to log an error.