Skip to content

Commit c294654

Browse files
gh-82535: Ignore address resolution failure in SysLogHandler constructor (GH-154504)
The address may be temporarily unresolvable when the handler is created. It is resolved again when a record is emitted. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 87b120f commit c294654

3 files changed

Lines changed: 26 additions & 1 deletion

File tree

Lib/logging/handlers.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -902,7 +902,11 @@ def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
902902
self.socktype = socktype
903903
self.timeout = timeout
904904
self.socket = None
905-
self.createSocket()
905+
# The address is resolved again when emitting an event.
906+
try:
907+
self.createSocket()
908+
except socket.gaierror:
909+
pass
906910

907911
def _connect_unixsocket(self, address):
908912
use_socktype = self.socktype

Lib/test/test_logging.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2211,6 +2211,24 @@ def tearDown(self):
22112211
self.server_class.address_family = socket.AF_INET
22122212
super(IPv6SysLogHandlerTest, self).tearDown()
22132213

2214+
@support.requires_working_socket()
2215+
class UnresolvableSysLogAddressTest(BaseTest):
2216+
2217+
"""Test for SysLogHandler with a temporarily unresolvable address."""
2218+
2219+
@patch('socket.getaddrinfo')
2220+
def test_unresolvable_address(self, mock_getaddrinfo):
2221+
# The address can be unresolvable when the handler is created.
2222+
mock_getaddrinfo.side_effect = socket.gaierror
2223+
hdlr = logging.handlers.SysLogHandler(('localhost', 514))
2224+
self.addCleanup(hdlr.close)
2225+
self.assertIsNone(hdlr.socket)
2226+
# It is resolved again when a record is emitted.
2227+
calls = mock_getaddrinfo.call_count
2228+
with support.captured_stderr():
2229+
hdlr.emit(logging.makeLogRecord({'msg': 'sp\xe4m'}))
2230+
self.assertGreater(mock_getaddrinfo.call_count, calls)
2231+
22142232
@support.requires_working_socket()
22152233
@threading_helper.requires_working_threading()
22162234
class HTTPHandlerTest(BaseTest):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:class:`logging.handlers.SysLogHandler` no longer fails
2+
if the address cannot be resolved when the handler is created.
3+
The address is resolved again when a record is emitted.

0 commit comments

Comments
 (0)