• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3#
4# Copyright (c) 2024 Huawei Device Co., Ltd.
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18import logging
19import re
20from typing import Any
21
22from pytest import FixtureRequest, fixture
23
24ARK_OUT, ARK_OUT_NAME = (logging.DEBUG + 5, "ARK_OUT")
25ARK_ERR, ARK_ERR_NAME = (logging.DEBUG + 6, "ARK_ERR")
26TRIO, TRIO_NAME = (logging.CRITICAL + 1, "TRIO_TASK")
27
28logging.addLevelName(ARK_OUT, ARK_OUT_NAME)
29logging.addLevelName(ARK_ERR, ARK_ERR_NAME)
30logging.addLevelName(TRIO, TRIO_NAME)
31
32
33class RichLogger(logging.LoggerAdapter):
34
35    def process(self, msg: Any, kwargs):
36        extra = kwargs.pop("extra", dict())
37        r = kwargs.pop("rich", None)
38        if r:
39            extra["rich"] = r
40        return msg, {**kwargs, "extra": extra}
41
42
43def logger(name: str) -> RichLogger:
44    return RichLogger(logging.getLogger(name))
45
46
47def _loggername_from_nodeid(nodeid: str) -> str:
48    if (pos := nodeid.find("[")) != -1:
49        nodeid = nodeid[:pos]
50    return re.sub(r"/|::", ".", nodeid)
51
52
53@fixture
54def log(request: FixtureRequest) -> RichLogger:
55    return RichLogger(logging.getLogger(_loggername_from_nodeid(request.node.nodeid)))
56