Changeset - 08163db8fa7d
[Not reviewed]
0 2 0
Lance Edgar (lance) - 11 years ago 2014-04-06 23:06:40
lance@edbob.org
Add `'uid'` and `'username'` to logger adapter context dict.
2 files changed with 14 insertions and 4 deletions:
0 comments (0 inline, 0 general)
rattail/logging.py
Show inline comments
 
@@ -28,9 +28,11 @@ Logging Utilities
 

	
 
from __future__ import absolute_import
 

	
 
import os
 
import sys
 
import logging
 
import socket
 
import sys
 
import getpass
 

	
 

	
 
class RattailAdapter(logging.LoggerAdapter):
 
@@ -43,6 +45,8 @@ class RattailAdapter(logging.LoggerAdapter):
 
    * ``'hostname'`` - The fully-qualified domain name of the host machine.
 
    * ``'hostip'`` - The IPv4 address of the host machine.
 
    * ``'argv'`` - The value of ``sys.argv`` (a list).
 
    * ``'uid'`` - The effective UID of the running process.
 
    * ``'username'`` - The login name of the effective user.
 
    """
 

	
 
    def __init__(self, logger):
 
@@ -51,6 +55,8 @@ class RattailAdapter(logging.LoggerAdapter):
 
            'hostname': hostname,
 
            'hostip':   socket.gethostbyname(hostname),
 
            'argv':     sys.argv,
 
            'uid':      os.getuid(),
 
            'username': getpass.getuser(),
 
            }
 
        # LoggerAdapter is a new-style class only as of Python 2.7; must not
 
        # use super() in case we're running on Python 2.6.
tests/test_logging.py
Show inline comments
 
@@ -10,13 +10,17 @@ from rattail import logging as rattail_logging
 

	
 
class TestLogging(TestCase):
 

	
 
    @patch('rattail.logging.os')
 
    @patch('rattail.logging.sys')
 
    @patch('rattail.logging.socket')
 
    def test_adapter_adds_all_context(self, socket, sys):
 
    @patch('rattail.logging.getpass')
 
    def test_adapter_adds_all_context(self, getpass, socket, sys, os):
 
        socket.getfqdn.return_value = 'testing.rattailproject.org'
 
        socket.gethostbyname.return_value = '127.0.0.1'
 
        sys.argv = ['just', 'testing']
 
        formatter = logging.Formatter(u"%(hostname)s %(hostip)s %(argv)s %(levelname)s %(message)s")
 
        os.getuid.return_value = 420
 
        getpass.getuser.return_value = 'joeschmoe'
 
        formatter = logging.Formatter(u"%(hostname)s %(hostip)s %(argv)s %(username)s %(uid)s %(levelname)s %(message)s")
 
        string = StringIO()
 
        handler = logging.StreamHandler(string)
 
        handler.setFormatter(formatter)
 
@@ -26,5 +30,5 @@ class TestLogging(TestCase):
 
        log = rattail_logging.RattailAdapter(log)
 
        self.assertEqual(string.getvalue(), "")
 
        log.debug("some random thing")
 
        self.assertEqual(string.getvalue(), u"testing.rattailproject.org 127.0.0.1 ['just', 'testing'] DEBUG some random thing\n")
 
        self.assertEqual(string.getvalue(), u"testing.rattailproject.org 127.0.0.1 ['just', 'testing'] joeschmoe 420 DEBUG some random thing\n")
 
        string.close()
0 comments (0 inline, 0 general)