1"""
2Sets up a custom :py:mod:`logging.Logger <logging>` for the project.
3:python:`from agents.tools.logging import logger` can be used to access the logger.
4"""
5
6import datetime
7import logging
8import os
9from typing import Optional
10
11USE_HYDRA_IF_POSSIBLE = True
12"""
13If :python:`True` and Hydra_ is available, :py:func:`make_logger` will
14return only a simple logger with just the name set.
15"""
16
17DEFAULT_NAME = "__main__"
18
19TRACE = 5
20"""Logging value below :py:obj:`logging.DEBUG`"""
21
22
23def log(text: str):
24 """
25 .. deprecated::
26 use :py:obj:`logger` instead
27
28 :meta private:
29 """
30 logging = (os.getenv("SHOW_LOGS") == "true") | False
31 if logging:
32 print(datetime.datetime.now(), text)
33
34
35def _setup_logger(name: str = "__main__", level: int = logging.DEBUG):
36 """Backup when Hydra_ is not available."""
37 logger = logging.getLogger(name)
38 logger.setLevel(logging.DEBUG)
39
40 # NOTE: un-comment a line to adjust the format
41 form = (
42 ""
43 # + "/////////////////////////\n" # When using multiple lines, e.g. for full path
44 + "[%(levelname)s][%(filename)s:%(lineno)d, %(funcName)s]: %(message)s" # note blank space before filename for IDE support
45 # + "\nin %(pathname)s %(lineno)d, %(funcName)s"
46 # + "\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\" # escaping so double the characters
47 )
48
49 formatter = logging.Formatter(form)
50 handler = logging.StreamHandler()
51 handler.setLevel(level)
52 handler.setFormatter(formatter)
53
54 logger.addHandler(handler)
55 return logger
56
57
[docs]
58def make_logger(name: Optional[str] = None, level: int = logging.DEBUG) -> logging.Logger:
59 """
60 Create a logger object with the specified name and log level.
61 If :py:obj:`USE_HYDRA_IF_POSSIBLE` is :python:`True` and the `hydra <https://hydra.cc/>`_
62 package is installed, this function will return a simple :py:class:`logging.Logger` with only
63 the **name** set.
64 Otherwise it will create a logger that is formatted based on :code:`_setup_logger`
65 from this file.
66
67 Parameters:
68 name: The name of the logger. Defaults to "__main__".
69 level: The log level for the logger. Defaults to :py:attr:`logging.DEBUG`.
70
71 Returns:
72 The logger object.
73 """
74 if not name:
75 name = DEFAULT_NAME
76 if USE_HYDRA_IF_POSSIBLE:
77 try:
78 import hydra # type: ignore # noqa
79
80 hydra_logging = True
81 except ImportError:
82 hydra_logging = False
83 else:
84 hydra_logging = False
85
86 if hydra_logging:
87 return logging.getLogger(DEFAULT_NAME)
88 return _setup_logger(name, level)
89
90
91logger: logging.Logger = make_logger()
92"""
93A constant logger object that can be imported and used throughout the project.
94"""