1# All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); you may 4# not use this file except in compliance with the License. You may obtain 5# a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12# License for the specific language governing permissions and limitations 13# under the License. 14 15import logging 16 17import fixtures 18 19 20class SetLogLevel(fixtures.Fixture): 21 """Override the log level for the named loggers, restoring their 22 previous value at the end of the test. 23 24 To use:: 25 26 from oslo_log import fixture as log_fixture 27 28 self.useFixture(log_fixture.SetLogLevel(['myapp.foo'], logging.DEBUG)) 29 30 :param logger_names: Sequence of logger names, as would be passed 31 to getLogger(). 32 :type logger_names: list(str) 33 :param level: Logging level, usually one of logging.DEBUG, 34 logging.INFO, etc. 35 :type level: int 36 """ 37 38 def __init__(self, logger_names, level): 39 self.logger_names = logger_names 40 self.level = level 41 42 def setUp(self): 43 super(SetLogLevel, self).setUp() 44 for name in self.logger_names: 45 # NOTE(dhellmann): Use the stdlib version of getLogger() 46 # so we get the logger and not any adaptor wrapping it. 47 logger = logging.getLogger(name) 48 self.addCleanup(logger.setLevel, logger.level) 49 logger.setLevel(self.level) 50