Skip to content

Commit

Permalink
always flush when logging messages
Browse files Browse the repository at this point in the history
  • Loading branch information
tigarmo committed Jul 6, 2023
1 parent 5f880f4 commit 77aa8a6
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions craft_cli/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ def _log(self, message: _MessageInfo) -> None:
# prepare the text with (maybe) the timestamp
timestamp_str = message.created_at.isoformat(sep=" ", timespec="milliseconds")
self.log.write(f"{timestamp_str} {message.text}\n")
self.log.flush()

def spin(self, message: _MessageInfo, spintext: str) -> None:
"""Write a line message including a spin text, only to a terminal."""
Expand Down
72 changes: 72 additions & 0 deletions tests/integration/test_logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import logging
import multiprocessing
import os
import sys
from textwrap import dedent

from craft_cli import emit, EmitterMode

logger = logging.getLogger()


def strip_timestamps(text: str) -> str:
lines = []
for line in text.splitlines():
lines.append(line.split(" ", maxsplit=2)[-1])
return "\n".join(lines)


def callable_func():
logger.info("Message 1 from CHILD process")
logger.info("Message 2 from CHILD process")


def test_logging_in_multiprocess(tmp_path):
logger.setLevel(logging.INFO)
emitter_log = tmp_path / "emitter_log.txt"
filehandler_log = tmp_path / "filehandler_log.txt"

filehandler = logging.FileHandler(filehandler_log)
os.set_inheritable(filehandler.stream.fileno(), True)
logger.addHandler(filehandler)
emit.init(mode=EmitterMode.QUIET, appname="testapp", greeting="hi", log_filepath=emitter_log)

logger.info("Message 1 from PARENT process")
logger.info("Message 2 from PARENT process")

child = multiprocessing.Process(target=callable_func)
child.start()
child.join()

logger.info("Message 3 from PARENT process")

emit.ended_ok()

emitter_logged = strip_timestamps(emitter_log.read_text())
filehandler_logged = filehandler_log.read_text()

if sys.platform == "linux":
# Expect two messages from the parent process, then two from the child process,
# then a final one from the parent again.
expected_text = dedent(
"""\
Message 1 from PARENT process
Message 2 from PARENT process
Message 1 from CHILD process
Message 2 from CHILD process
Message 3 from PARENT process
"""
)
else:
# Messages from the child process are NOT logged in non-Linux platforms. This
# is not by design, but a record of the current expected behavior.
expected_text = dedent(
"""\
Message 1 from PARENT process
Message 2 from PARENT process
Message 3 from PARENT process
"""
)

assert emitter_logged == "hi\n" + expected_text.rstrip()
assert filehandler_logged == expected_text

0 comments on commit 77aa8a6

Please sign in to comment.