| #!/usr/bin/env python3 |
| # |
| # Copyright 2022 The Fuchsia Authors |
| # |
| # Licensed under the Apache License, Version 2.0 (the "License"); |
| # you may not use this file except in compliance with the License. |
| # You may obtain a copy of the License at |
| # |
| # http://www.apache.org/licenses/LICENSE-2.0 |
| # |
| # Unless required by applicable law or agreed to in writing, software |
| # distributed under the License is distributed on an "AS IS" BASIS, |
| # 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 |
| from types import TracebackType |
| |
| |
| class LogLevel: |
| """Sets the logging level threshold for logger within this context. |
| |
| Logging messages which are equal or less severe than level will be ignored. |
| See https://docs.python.org/3/library/logging.html#levels for a list of |
| levels. |
| """ |
| |
| def __init__( |
| self, logger: logging.Logger | logging.LoggerAdapter, level: int |
| ) -> None: |
| self._logger = logger |
| if isinstance(logger, logging.Logger): |
| self._old_level = logger.level |
| else: |
| self._old_level = logger.logger.level |
| self._new_level = level |
| |
| def __enter__(self) -> logging.Logger | logging.LoggerAdapter: |
| self._logger.setLevel(self._new_level) |
| return self._logger |
| |
| def __exit__( |
| self, |
| _exit_type: type[BaseException] | None, |
| _exit_value: BaseException | None, |
| _exit_traceback: TracebackType | None, |
| ) -> None: |
| self._logger.setLevel(self._old_level) |