diff --git a/autopush/logging.py b/autopush/logging.py index bb90210d..fd9b3ea1 100644 --- a/autopush/logging.py +++ b/autopush/logging.py @@ -8,6 +8,7 @@ import sys import time import threading +from typing import Any # noqa import boto3 import raven @@ -17,6 +18,7 @@ from twisted.logger import ( formatEvent, formatEventAsClassicLogText, + globalLogBeginner, globalLogPublisher, LogLevel, ILogObserver @@ -53,6 +55,25 @@ ]) +# whether the global LogBeginner.beginLoggingTo has been called: it +# should only be called once +began_logging = False + + +def begin_or_register(observer): + """Register observer with the global LogPublisher + + Registers via the global LogBeginner the first time called. + """ + # type: (Any) -> None + global began_logging + if not began_logging: + globalLogBeginner.beginLoggingTo([observer], redirectStandardIO=False) + began_logging = True + else: + globalLogPublisher.addObserver(observer) + + @implementer(ILogObserver) class PushLogger(object): """Twisted LogObserver implementation @@ -182,7 +203,7 @@ def start(self): self._output = io.open(self._filename, "a", encoding="utf-8") if self.firehose: self.firehose.start() - globalLogPublisher.addObserver(self) + begin_or_register(self) def stop(self): globalLogPublisher.removeObserver(self) diff --git a/autopush/tests/test_integration.py b/autopush/tests/test_integration.py index 9828e756..6f017ecb 100644 --- a/autopush/tests/test_integration.py +++ b/autopush/tests/test_integration.py @@ -45,6 +45,7 @@ get_month, has_connected_this_month ) +from autopush.logging import begin_or_register from autopush.main import endpoint_paths from autopush.settings import AutopushSettings from autopush.utils import base64url_encode @@ -372,7 +373,7 @@ def setUp(self): ) self.logs = TestingLogObserver() - globalLogPublisher.addObserver(self.logs) + begin_or_register(self.logs) router_table = os.environ.get("ROUTER_TABLE", "router_int_test") storage_table = os.environ.get("STORAGE_TABLE", "storage_int_test")