1# SPDX-License-Identifier: MIT OR Apache-2.0
2# This file is dual licensed under the terms of the Apache License, Version
3# 2.0, and the MIT License. See the LICENSE file in the root of this
4# repository for complete details.
5
6"""
7Generic bound logger that can wrap anything.
8"""
9
10from __future__ import annotations
11
12from functools import partial
13from typing import Any
14
15from structlog._base import BoundLoggerBase
16
17
18class BoundLogger(BoundLoggerBase):
19 """
20 A generic BoundLogger that can wrap anything.
21
22 Every unknown method will be passed to the wrapped *logger*. If that's too
23 much magic for you, try `structlog.stdlib.BoundLogger` or
24 `structlog.twisted.BoundLogger` which also take advantage of knowing the
25 wrapped class which generally results in better performance.
26
27 Not intended to be instantiated by yourself. See
28 :func:`~structlog.wrap_logger` and :func:`~structlog.get_logger`.
29 """
30
31 def __getattr__(self, method_name: str) -> Any:
32 """
33 If not done so yet, wrap the desired logger method & cache the result.
34 """
35 if method_name == "__deepcopy__":
36 return None
37
38 wrapped = partial(self._proxy_to_logger, method_name)
39 setattr(self, method_name, wrapped)
40
41 return wrapped
42
43 def __getstate__(self) -> dict[str, Any]:
44 """
45 Our __getattr__ magic makes this necessary.
46 """
47 return self.__dict__
48
49 def __setstate__(self, state: dict[str, Any]) -> None:
50 """
51 Our __getattr__ magic makes this necessary.
52 """
53 for k, v in state.items():
54 setattr(self, k, v)