Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Put python's logs into Trial when running unit tests #3319

Merged
merged 3 commits into from
Jun 4, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions tests/unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,30 @@
# limitations under the License.
import twisted
from twisted.trial import unittest
from synapse.util.logcontext import LoggingContextFilter
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ftr, PEP8 has some opinions on import order which we try to follow - in this case that means that imports from synapse go after those from twisted. OTOH this file already breaks the convention by putting import logging at the end so <shrug>

from twisted.logger import Logger, LogLevel
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should use absolute names for these (import twisted.logger; tx_log=twisted.logger.Logger()) to reduce confusion between twisted and stdlib logging infrastructure


import logging

# logging doesn't have a "don't log anything at all EVARRRR setting,
# but since the highest value is 50, 1000000 should do ;)
NEVER = 1000000
# Set up putting Synapse's logs into Trial's.
rootLogger = logging.getLogger()

handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
"%(levelname)s:%(name)s:%(message)s [%(pathname)s:%(lineno)d]"
))
logging.getLogger().addHandler(handler)
logging.getLogger().setLevel(NEVER)
logging.getLogger("synapse.storage.SQL").setLevel(NEVER)
logging.getLogger("synapse.storage.txn").setLevel(NEVER)
log_format = (
"%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s"
" - %(message)s"
)

class ToTwistedHandler(logging.Handler):
tx_log = Logger()
def emit(self, record):
log_entry = self.format(record)
self.tx_log.emit(LogLevel.levelWithName(record.levelname.lower()), log_entry)

handler = ToTwistedHandler()
formatter = logging.Formatter(log_format)
handler.setFormatter(formatter)
handler.addFilter(LoggingContextFilter(request=""))
rootLogger.addHandler(handler)


def around(target):
Expand Down Expand Up @@ -61,7 +70,7 @@ def __init__(self, methodName, *args, **kwargs):

method = getattr(self, methodName)

level = getattr(method, "loglevel", getattr(self, "loglevel", NEVER))
level = getattr(method, "loglevel", getattr(self, "loglevel", logging.ERROR))

@around(self)
def setUp(orig):
Expand Down