changeset 1008:d70d4fe5c5f8

core (log): added magic %(profile)s key to log_fmt: if %(profile)s is used in log_fmt, SàT try to find profile value using introspection. This is for debugging purpose only, *DO NOT* use in production. This key don't work (yet ?) with standard backend, and will not work in every frontend.
author Goffi <goffi@goffi.org>
date Mon, 05 May 2014 18:58:34 +0200
parents a7d33c7a8277
children d1084f7e56a5
files src/core/log.py
diffstat 1 files changed, 36 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/src/core/log.py	Mon May 05 18:58:34 2014 +0200
+++ b/src/core/log.py	Mon May 05 18:58:34 2014 +0200
@@ -94,7 +94,18 @@
         except AttributeError:
             if self.filter_name is not None:
                 raise ValueError("Bad filter: filters must have a .filter method")
-        return self.fmt % record if self.fmt is not None else message
+        try:
+            return self.fmt % record
+        except TypeError:
+            return message
+        except KeyError as e:
+            if e.args[0] == 'profile':
+                # XXX: %(profile)s use some magic with introspection, for debugging purpose only *DO NOT* use in production
+                record['profile'] = _getProfile()
+                return self.fmt % record
+            else:
+                raise e
+
 
     def debug(self, msg):
         self.log(C.LOG_LVL_DEBUG, msg)
@@ -159,6 +170,30 @@
         return self.filter(log_record) == 1
 
 
+def _getProfile():
+    """Try to find profile value using introspection"""
+    import inspect
+    stack = inspect.stack()
+    current_path = stack[0][1]
+    for frame_data in stack[:-1]:
+        if frame_data[1] != current_path:
+            break
+
+    frame = frame_data[0]
+    args = inspect.getargvalues(frame)
+    try:
+        profile = args.locals.get('profile') or args.locals['profile_key']
+    except (TypeError, KeyError):
+        try:
+            try:
+                profile = args.locals['self'].profile
+            except AttributeError:
+                profile = args.locals['self'].parent.profile
+        except Exception:
+            # we can't find profile, we return an empty value
+            profile = ''
+    return profile
+
 def _ansiColors(level, message):
     """Colorise message depending on level for terminals