|
14 | 14 | import mitogen.utils |
15 | 15 | from mitogen.core import b |
16 | 16 |
|
| 17 | +PY2 = sys.version_info[0] == 2 |
| 18 | +if PY2: |
| 19 | + |
| 20 | + def logging_getLogRecordFactory(): |
| 21 | + return logging.LogRecord |
| 22 | + |
| 23 | + def logging_setLogRecordFactory(factory): |
| 24 | + logging.LogRecord = factory |
| 25 | + |
| 26 | +else: |
| 27 | + logging_getLogRecordFactory = logging.getLogRecordFactory |
| 28 | + logging_setLogRecordFactory = logging.setLogRecordFactory |
| 29 | + |
17 | 30 |
|
18 | 31 | def ping(): |
19 | 32 | pass |
20 | 33 |
|
21 | 34 |
|
| 35 | +def log_test(): |
| 36 | + logging.getLogger(__name__).info("This is a test") |
| 37 | + |
| 38 | + |
22 | 39 | class BufferingTest(testlib.TestCase): |
23 | 40 | klass = mitogen.core.LogHandler |
24 | 41 |
|
@@ -89,6 +106,36 @@ def test_earliest_messages_logged_via(self): |
89 | 106 | expect = 'Parent is context %s (%s)' % (c1.context_id, 'parent') |
90 | 107 | self.assertIn(expect, logs) |
91 | 108 |
|
| 109 | + |
| 110 | +class LogRecordFactoryTest(testlib.RouterMixin, testlib.TestCase): |
| 111 | + def setUp(self): |
| 112 | + super(LogRecordFactoryTest, self).setUp() |
| 113 | + self.original_factory = logging_getLogRecordFactory() |
| 114 | + |
| 115 | + def tearDown(self): |
| 116 | + logging_setLogRecordFactory(self.original_factory) |
| 117 | + super(LogRecordFactoryTest, self).tearDown() |
| 118 | + |
| 119 | + def test_logrecordfactory(self): |
| 120 | + # Change logging factory and add a custom attribute |
| 121 | + old_factory = logging_getLogRecordFactory() |
| 122 | + |
| 123 | + def record_factory(*args, **kwargs): |
| 124 | + record = old_factory(*args, **kwargs) |
| 125 | + record.custom_attribute = 0xDEADBEEF |
| 126 | + return record |
| 127 | + |
| 128 | + logging_setLogRecordFactory(record_factory) |
| 129 | + c1 = self.router.local(name="c1") |
| 130 | + log = testlib.LogCapturer( |
| 131 | + __name__, formatter=logging.Formatter("%(custom_attribute)x - %(message)s") |
| 132 | + ) |
| 133 | + log.start() |
| 134 | + c1.call(log_test) |
| 135 | + logs = log.stop() |
| 136 | + self.assertIn("deadbeef - This is a test", logs) |
| 137 | + |
| 138 | + |
92 | 139 | StartupTest = unittest.skipIf( |
93 | 140 | condition=sys.version_info < (2, 7) or sys.version_info >= (3, 6), |
94 | 141 | reason="Message log flaky on Python < 2.7 or >= 3.6" |
|
0 commit comments