| 1 |
import logging |
| 2 |
|
| 3 |
class SessionLoggerAdapter(logging.LoggerAdapter): |
| 4 |
"""Logger adapter that automatically adds session information to logs.""" |
| 5 |
|
| 6 |
def process(self, msg, kwargs): |
| 7 |
if 'session' not in self.extra or self.extra['session'] is None: |
| 8 |
return msg, kwargs |
| 9 |
session = self.extra['session'] |
| 10 |
prefix = "" |
| 11 |
# All Session instances have an id. SSHSessions have a host as well. |
| 12 |
if hasattr(session, 'host'): |
| 13 |
prefix += "host %s " % session.host |
| 14 |
|
| 15 |
if session.id is not None: |
| 16 |
prefix += "session-id %s" % session.id |
| 17 |
else: |
| 18 |
prefix += "session 0x%x" % id(session) |
| 19 |
|
| 20 |
# Pass the session information through to the LogRecord itself |
| 21 |
if 'extra' not in kwargs: |
| 22 |
kwargs['extra'] = self.extra |
| 23 |
else: |
| 24 |
kwargs['extra'].update(self.extra) |
| 25 |
|
| 26 |
return "[%s] %s" % (prefix, msg), kwargs |