Skip to content

Commit edd9509

Browse files
gh-82535: Ignore address resolution failure in SysLogHandler constructor
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 a2a8466 commit edd9509

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
@@ -901,7 +901,11 @@ def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
901901
self.socktype = socktype
902902
self.timeout = timeout
903903
self.socket = None
904-
self.createSocket()
904+
# The address is resolved again when emitting an event.
905+
try:
906+
self.createSocket()
907+
except socket.gaierror:
908+
pass
905909

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

Lib/test/test_logging.py

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

2158+
@support.requires_working_socket()
2159+
class UnresolvableSysLogAddressTest(BaseTest):
2160+
2161+
"""Test for SysLogHandler with a temporarily unresolvable address."""
2162+
2163+
@patch('socket.getaddrinfo')
2164+
def test_unresolvable_address(self, mock_getaddrinfo):
2165+
# The address can be unresolvable when the handler is created.
2166+
mock_getaddrinfo.side_effect = socket.gaierror
2167+
hdlr = logging.handlers.SysLogHandler(('localhost', 514))
2168+
self.addCleanup(hdlr.close)
2169+
self.assertIsNone(hdlr.socket)
2170+
# It is resolved again when a record is emitted.
2171+
calls = mock_getaddrinfo.call_count
2172+
with support.captured_stderr():
2173+
hdlr.emit(logging.makeLogRecord({'msg': 'sp\xe4m'}))
2174+
self.assertGreater(mock_getaddrinfo.call_count, calls)
2175+
21582176
@support.requires_working_socket()
21592177
@threading_helper.requires_working_threading()
21602178
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)