Skip to content

Commit 8a83571

Browse files
authored
🎨 Replace print statements in Banner with info log (#3643)
1 parent 609be86 commit 8a83571

File tree

4 files changed

+71
-57
lines changed

4 files changed

+71
-57
lines changed

acapy_agent/config/banner.py

Lines changed: 60 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,29 @@
11
"""Module to contain logic to generate the banner for ACA-py."""
22

3-
import sys
3+
import logging
44
import textwrap
55
from contextlib import contextmanager
66
from enum import Enum, auto
77
from typing import Optional, TextIO
88

9+
logger = logging.getLogger(__name__)
10+
911

1012
@contextmanager
1113
def Banner(border: str, length: int, file: Optional[TextIO] = None):
1214
"""Context manager to generate a banner for ACA-py."""
1315
banner = _Banner(border, length, file)
14-
banner.print_border()
16+
banner.add_border()
1517
yield banner
16-
banner.print_border()
18+
banner.add_border()
19+
20+
# Join all lines with newlines and log them
21+
banner_text = "\n".join(banner.lines)
22+
banner_text = f"\n{banner_text.strip()}\n" # Start/end with a newline
23+
if file:
24+
print(banner_text, file=file)
25+
else:
26+
logger.info(banner_text)
1727

1828

1929
class _Banner:
@@ -34,11 +44,12 @@ def __init__(self, border: str, length: int, file: Optional[TextIO] = None):
3444
"""
3545
self.border = border
3646
self.length = length
37-
self.file = file or sys.stdout
47+
self.file = file
48+
self.lines = []
3849

39-
def _print(self, text: str):
40-
"""Print value."""
41-
print(text, file=self.file)
50+
def _add_line(self, text: str):
51+
"""Add a line to the banner."""
52+
self.lines.append(text)
4253

4354
def _lr_pad(self, content: str):
4455
"""Pad string content with defined border character.
@@ -48,80 +59,87 @@ def _lr_pad(self, content: str):
4859
"""
4960
return f"{self.border}{self.border} {content} {self.border}{self.border}"
5061

51-
def _print_line(self, text: str, alignment: align = align.LEFT):
52-
"""Print line."""
62+
def _format_line(self, text: str, alignment: align = align.LEFT):
63+
"""Format a line with the specified alignment."""
5364
lines = textwrap.wrap(text, width=self.length)
65+
formatted_lines = []
66+
5467
for line in lines:
5568
if len(line) < self.length:
5669
if alignment == self.align.LEFT:
57-
left = ""
58-
right = " " * (self.length - len(line))
70+
# Left alignment
71+
formatted_line = f"{line:<{self.length}}"
5972
elif alignment == self.align.CENTER:
60-
left = " " * ((self.length - len(line)) // 2)
61-
right = " " * ((self.length - len(line)) // 2)
62-
if len(line) % 2 != 0:
63-
right += " "
73+
# Center alignment
74+
total_padding = self.length - len(line)
75+
left_padding = total_padding // 2
76+
right_padding = total_padding - left_padding
77+
formatted_line = f"{' ' * left_padding}{line}{' ' * right_padding}"
6478
elif alignment == self.align.RIGHT:
65-
left = " " * (self.length - len(line))
66-
right = ""
79+
# Right alignment
80+
formatted_line = f"{line:>{self.length}}"
6781
else:
6882
raise ValueError(f"Invalid alignment: {alignment}")
69-
line = f"{left}{line}{right}"
70-
self._print(self._lr_pad(line))
83+
else:
84+
formatted_line = line
85+
86+
formatted_lines.append(self._lr_pad(formatted_line))
87+
88+
return formatted_lines
7189

72-
def print_border(self):
73-
"""Print a full line using the border character."""
74-
self._print(self.border * (self.length + 6))
90+
def add_border(self):
91+
"""Add a full line using the border character."""
92+
self._add_line(self.border * (self.length + 6))
7593

7694
def title(self, title, spacing_after: int = 2):
77-
"""Print the main title element."""
78-
self._print_line(title, self.align.CENTER)
95+
"""Add the main title element."""
96+
self.lines.extend(self._format_line(title, self.align.CENTER))
7997
for _ in range(spacing_after):
8098
self.spacer()
8199

82100
def spacer(self):
83-
"""Print an empty line with the border character only."""
84-
self._print(self._lr_pad(" " * self.length))
101+
"""Add an empty line with the border character only."""
102+
self._add_line(self._lr_pad(" " * self.length))
85103

86104
def hr(self, char: str = "-"):
87-
"""Print a line with a horizontal rule."""
88-
self._print(self._lr_pad(char * self.length))
105+
"""Add a line with a horizontal rule."""
106+
self._add_line(self._lr_pad(char * self.length))
89107

90108
def subtitle(self, title: str, spacing_after: int = 1):
91-
"""Print a subtitle for a section."""
109+
"""Add a subtitle for a section."""
92110
title += ":"
93-
self._print_line(title, self.align.LEFT)
111+
self.lines.extend(self._format_line(title, self.align.LEFT))
94112
for _ in range(spacing_after):
95113
self.spacer()
96114

97115
def list(self, items, spacing_after: int = 1):
98-
"""Print a list of items, prepending a dash to each item."""
116+
"""Add a list of items, prepending a dash to each item."""
99117
for item in items:
100-
self._print_line(f" - {item}", self.align.LEFT)
118+
self.lines.extend(self._format_line(f" - {item}", self.align.LEFT))
101119

102120
for _ in range(spacing_after):
103121
self.spacer()
104122

105123
def version(self, version):
106-
"""Print the current ``version``."""
124+
"""Add the current ``version``."""
107125
version = f"ver: {version}"
108-
self._print_line(version, self.align.RIGHT)
126+
self.lines.extend(self._format_line(version, self.align.RIGHT))
109127

110128
def print(self, text: str):
111-
"""Print a line of text."""
112-
self._print_line(text, self.align.LEFT)
129+
"""Add a line of text."""
130+
self.lines.extend(self._format_line(text, self.align.LEFT))
113131

114132
def left(self, text: str):
115-
"""Print a line of text left aligned.
133+
"""Add a line of text left aligned.
116134
117135
Same as `print` method.
118136
"""
119-
self._print_line(text, self.align.LEFT)
137+
self.lines.extend(self._format_line(text, self.align.LEFT))
120138

121139
def centered(self, text: str):
122-
"""Print a line of text centered."""
123-
self._print_line(text, self.align.CENTER)
140+
"""Add a line of text centered."""
141+
self.lines.extend(self._format_line(text, self.align.CENTER))
124142

125143
def right(self, text: str):
126-
"""Print a line of text right aligned."""
127-
self._print_line(text, self.align.RIGHT)
144+
"""Add a line of text right aligned."""
145+
self.lines.extend(self._format_line(text, self.align.RIGHT))

acapy_agent/config/logging/configurator.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import logging
66
import logging.config
77
import os
8-
import sys
98
from importlib import resources
109
from logging.config import (
1110
_clearExistingHandlers,
@@ -286,7 +285,6 @@ def print_banner(
286285
border_character: (Default value = ":") Character to use in banner
287286
border
288287
"""
289-
print()
290288
with Banner(border=border_character, length=banner_length) as banner:
291289
# Title
292290
banner.title(agent_label or "ACA")
@@ -348,14 +346,10 @@ def print_banner(
348346

349347
banner.version(__version__)
350348

351-
print()
352-
print("Listening...")
353-
print()
354-
355349
@classmethod
356350
def print_notices(cls, settings: Settings):
357351
"""Print notices and warnings."""
358-
with Banner(border=":", length=80, file=sys.stderr) as banner:
352+
with Banner(border=":", length=80) as banner:
359353
if settings.get("wallet.type", "in_memory").lower() == "indy":
360354
banner.centered("⚠ DEPRECATION NOTICE: ⚠")
361355
banner.hr()
@@ -392,4 +386,3 @@ def print_notices(cls, settings: Settings):
392386
"and support will be removed in a future release; "
393387
"use RFC 0454: Present Proof 2.0 instead."
394388
)
395-
print()

acapy_agent/config/tests/test_logging.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import contextlib
2-
from io import BufferedReader, StringIO, TextIOWrapper
1+
from io import BufferedReader, TextIOWrapper
32
from tempfile import NamedTemporaryFile
43
from unittest import IsolatedAsyncioTestCase, mock
54

@@ -87,13 +86,13 @@ def test_configure_with_multitenant_with_yaml_file(self):
8786
)
8887

8988
def test_banner_did(self):
90-
stdout = StringIO()
9189
mock_http = mock.MagicMock(scheme="http", host="1.2.3.4", port=8081)
9290
mock_https = mock.MagicMock(schemes=["https", "archie"])
9391
mock_admin_server = mock.MagicMock(host="1.2.3.4", port=8091)
94-
with contextlib.redirect_stdout(stdout):
95-
test_label = "Aries Cloud Agent"
96-
test_did = "55GkHamhTU1ZbTbV2ab9DE"
92+
test_label = "Aries Cloud Agent"
93+
test_did = "55GkHamhTU1ZbTbV2ab9DE"
94+
95+
with self.assertLogs(level="INFO") as log:
9796
test_module.LoggingConfigurator.print_banner(
9897
test_label,
9998
{"in": mock_http},
@@ -104,7 +103,9 @@ def test_banner_did(self):
104103
test_module.LoggingConfigurator.print_banner(
105104
test_label, {"in": mock_http}, {"out": mock_https}, test_did
106105
)
107-
output = stdout.getvalue()
106+
107+
# Join all log records and check if DID is present
108+
output = "\n".join(log.output)
108109
assert test_did in output
109110

110111
def test_load_resource(self):

acapy_agent/core/conductor.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,8 @@ async def start(self) -> None:
592592
await self.root_profile.notify(STARTUP_EVENT_TOPIC, {})
593593
LOGGER.debug("Startup notification sent.")
594594

595+
LOGGER.info("Listening...")
596+
595597
async def stop(self, timeout=1.0):
596598
"""Stop the agent."""
597599
LOGGER.info("Stopping the Conductor agent.")

0 commit comments

Comments
 (0)