Wei-Yu Chen | 49950b9 | 2021-11-08 19:19:18 +0800 | [diff] [blame] | 1 | """ |
| 2 | Copyright 2020 The Magma Authors. |
| 3 | |
| 4 | This source code is licensed under the BSD-style license found in the |
| 5 | LICENSE file in the root directory of this source tree. |
| 6 | |
| 7 | Unless required by applicable law or agreed to in writing, software |
| 8 | distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | See the License for the specific language governing permissions and |
| 11 | limitations under the License. |
| 12 | """ |
| 13 | |
| 14 | import logging |
| 15 | |
| 16 | |
| 17 | class MsgCounterHandler(logging.Handler): |
| 18 | """ Register this handler to logging to count the logs by level """ |
| 19 | |
| 20 | count_by_level = None |
| 21 | |
| 22 | def __init__(self, *args, **kwargs): |
| 23 | super(MsgCounterHandler, self).__init__(*args, **kwargs) |
| 24 | self.count_by_level = {} |
| 25 | |
| 26 | def emit(self, record: logging.LogRecord): |
| 27 | level = record.levelname |
| 28 | if (level not in self.count_by_level): |
| 29 | self.count_by_level[level] = 0 |
| 30 | self.count_by_level[level] += 1 |
| 31 | |
| 32 | def pop_error_count(self) -> int: |
| 33 | error_count = self.count_by_level.get('ERROR', 0) |
| 34 | self.count_by_level['ERROR'] = 0 |
| 35 | return error_count |