Debian Codegraph @

tests/test_logging.py

raw
1 # Copyright 2024 The HuggingFace Team. All rights reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain 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,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 import inspect
15 import logging
16 import os
17
18 import pytest
19
20 from accelerate import Accelerator
21 from accelerate.logging import get_logger
22 from accelerate.state import AcceleratorState
23
24
25 def current_lineno() -> int:
26 # A simple helper that returns the lineno of its call-site.
27 caller_frame = inspect.currentframe().f_back
28 caller_info = inspect.getframeinfo(caller_frame)
29 return caller_info.lineno
30
31
32 class CustomLogger(logging.LoggerAdapter):
33 # Mocks a user-defined custom logger wrapper that sets `stacklevel=3`.
34 def log(self, level, msg, *args, **kwargs):
35 # E.g. the user wants to modify `stacklevel`, `accelerate.logging`
36 # should respect the user's `stacklevel`. For the specific value
37 # of `3`, calling `CustomLogger.log()`, etc., should log that callsite,
38 # rather than the callsite of the following `self.logger.log()`.
39 kwargs["stacklevel"] = 3
40 self.logger.log(level, msg, *args, **kwargs)
41
42
43 @pytest.fixture(scope="module")
44 def accelerator():
45 accelerator = Accelerator()
46 yield accelerator
47 AcceleratorState._reset_state(True)
48
49
50 @pytest.mark.usefixtures("accelerator")
51 def test_log_stack(caplog):
52 logger = get_logger(__name__)
53 logging.basicConfig(
54 format="%(filename)s:%(name)s:%(lineno)s:%(funcName)s - %(message)s",
55 datefmt="%m/%d %H:%M:%S",
56 )
57
58 message = "Test"
59 expected_message, _ = logger.process(message, {})
60 lineno = current_lineno() + 1 # the next line is the actual callsite
61 logger.warning(message)
62
63 assert len(caplog.records) == 1
64 rec = caplog.records[0]
65 assert rec.levelname == logging.getLevelName(logging.WARNING)
66 assert rec.filename == os.path.basename(__file__)
67 assert rec.name == __name__
68 assert rec.lineno == lineno
69 assert rec.funcName == test_log_stack.__name__
70 assert rec.message == expected_message
71
72
73 @pytest.mark.usefixtures("accelerator")
74 def test_custom_stacklevel(caplog):
75 wrapped_logger = get_logger(__name__)
76 logging.basicConfig(
77 format="%(filename)s:%(name)s:%(lineno)s:%(funcName)s - %(message)s",
78 datefmt="%m/%d %H:%M:%S",
79 )
80 logger = CustomLogger(wrapped_logger, {})
81
82 message = "Test"
83 expected_message, _ = wrapped_logger.process(message, {})
84 lineno = current_lineno() + 1 # the next line is the actual callsite
85 logger.warning(message)
86
87 # `CustomLogger.log` set custom `stacklevel=3`, so `logger.warning` should
88 # log its callsite (rather than those of the `warpped_logger`).
89 assert len(caplog.records) == 1
90 rec = caplog.records[0]
91 assert rec.levelname == logging.getLevelName(logging.WARNING)
92 assert rec.filename == os.path.basename(__file__)
93 assert rec.name == __name__
94 assert rec.lineno == lineno
95 assert rec.funcName == test_custom_stacklevel.__name__
96 assert rec.message == expected_message