Skip to content

Commit fa16e1b

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 4d92c53 commit fa16e1b

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

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

Lib/test/test_logging.py

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

2150+
@support.requires_working_socket()
2151+
class UnresolvableSysLogAddressTest(BaseTest):
2152+
2153+
"""Test for SysLogHandler with a temporarily unresolvable address."""
2154+
2155+
@patch('socket.getaddrinfo')
2156+
def test_unresolvable_address(self, mock_getaddrinfo):
2157+
# The address can be unresolvable when the handler is created.
2158+
mock_getaddrinfo.side_effect = socket.gaierror
2159+
hdlr = logging.handlers.SysLogHandler(('localhost', 514))
2160+
self.addCleanup(hdlr.close)
2161+
self.assertIsNone(hdlr.socket)
2162+
# It is resolved again when a record is emitted.
2163+
calls = mock_getaddrinfo.call_count
2164+
with support.captured_stderr():
2165+
hdlr.emit(logging.makeLogRecord({'msg': 'sp\xe4m'}))
2166+
self.assertGreater(mock_getaddrinfo.call_count, calls)
2167+
21502168
@support.requires_working_socket()
21512169
@threading_helper.requires_working_threading()
21522170
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)