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 #+ "/////////////////////////\n" # When using multiple lines, e.g. for full path
43 + "[%(levelname)s][%(filename)s:%(lineno)d, %(funcName)s]: %(message)s" # note blank space before filename for IDE support
44 #+ "\nin %(pathname)s %(lineno)d, %(funcName)s"
45 #+ "\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\" # escaping so double the characters
46 )
47
48 formatter = logging.Formatter(form)
49 handler = logging.StreamHandler()
50 handler.setLevel(level)
51 handler.setFormatter(formatter)
52
53 logger.addHandler(handler)
54 return logger
55
56
[docs]
57def make_logger(name: Optional[str] = None, level: int = logging.DEBUG) -> logging.Logger:
58 """
59 Create a logger object with the specified name and log level.
60 If :py:obj:`USE_HYDRA_IF_POSSIBLE` is :python:`True` and the `hydra <https://hydra.cc/>`_
61 package is installed, this function will return a simple :py:class:`logging.Logger` with only
62 the **name** set.
63 Otherwise it will create a logger that is formatted based on :code:`_setup_logger`
64 from this file.
65
66 Parameters:
67 name: The name of the logger. Defaults to "__main__".
68 level: The log level for the logger. Defaults to :py:attr:`logging.DEBUG`.
69
70 Returns:
71 The logger object.
72 """
73 if not name:
74 name = DEFAULT_NAME
75 if USE_HYDRA_IF_POSSIBLE:
76 try:
77 import hydra # type: ignore # noqa
78 hydra_logging = True
79 except ImportError:
80 hydra_logging = False
81 else:
82 hydra_logging = False
83
84 if hydra_logging:
85 return logging.getLogger(DEFAULT_NAME)
86 return _setup_logger(name, level)
87
88
89logger: logging.Logger = make_logger()
90"""
91A constant logger object that can be imported and used throughout the project.
92"""