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

Commit

Permalink
Put python's logs into Trial when running unit tests (#3319)
Browse files Browse the repository at this point in the history
  • Loading branch information
hawkowl authored Jun 4, 2018
1 parent 86accac commit 5dbf305
Showing 1 changed file with 27 additions and 13 deletions.
40 changes: 27 additions & 13 deletions tests/unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,37 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging

import twisted
import twisted.logger
from twisted.trial import unittest

import logging
from synapse.util.logcontext import LoggingContextFilter

# Set up putting Synapse's logs into Trial's.
rootLogger = logging.getLogger()

log_format = (
"%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s"
)


class ToTwistedHandler(logging.Handler):
tx_log = twisted.logger.Logger()

def emit(self, record):
log_entry = self.format(record)
log_level = record.levelname.lower().replace('warning', 'warn')
self.tx_log.emit(twisted.logger.LogLevel.levelWithName(log_level), log_entry)

# 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

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)
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 +75,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

0 comments on commit 5dbf305

Please sign in to comment.