Skip to content

Commit 741d1fa

Browse files
serhiy-storchakaclaude
authored andcommitted
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. (cherry picked from commit c294654) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 518f743 commit 741d1fa

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
@@ -878,7 +878,11 @@ def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
878878
self.socktype = socktype
879879
self.timeout = timeout
880880
self.socket = None
881-
self.createSocket()
881+
# The address is resolved again when emitting an event.
882+
try:
883+
self.createSocket()
884+
except socket.gaierror:
885+
pass
882886

883887
def _connect_unixsocket(self, address):
884888
use_socktype = self.socktype

Lib/test/test_logging.py

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

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