Wei-Yu Chen | ad55cb8 | 2022-02-15 20:07:01 +0800 | [diff] [blame^] | 1 | # SPDX-FileCopyrightText: 2020 The Magma Authors. |
| 2 | # SPDX-FileCopyrightText: 2022 Open Networking Foundation <support@opennetworking.org> |
| 3 | # |
| 4 | # SPDX-License-Identifier: BSD-3-Clause |
Wei-Yu Chen | 49950b9 | 2021-11-08 19:19:18 +0800 | [diff] [blame] | 5 | |
| 6 | import logging |
| 7 | |
| 8 | |
| 9 | class MsgCounterHandler(logging.Handler): |
| 10 | """ Register this handler to logging to count the logs by level """ |
| 11 | |
| 12 | count_by_level = None |
| 13 | |
| 14 | def __init__(self, *args, **kwargs): |
| 15 | super(MsgCounterHandler, self).__init__(*args, **kwargs) |
| 16 | self.count_by_level = {} |
| 17 | |
| 18 | def emit(self, record: logging.LogRecord): |
| 19 | level = record.levelname |
| 20 | if (level not in self.count_by_level): |
| 21 | self.count_by_level[level] = 0 |
| 22 | self.count_by_level[level] += 1 |
| 23 | |
| 24 | def pop_error_count(self) -> int: |
| 25 | error_count = self.count_by_level.get('ERROR', 0) |
| 26 | self.count_by_level['ERROR'] = 0 |
| 27 | return error_count |