Safemotion Lib
Loading...
Searching...
No Matches
Classes | Functions | Variables
fastreid.utils.logger Namespace Reference

Classes

class  _ColorfulFormatter
 

Functions

 setup_logger (output=None, distributed_rank=0, *color=True, name="fastreid", abbrev_name=None)
 
 _cached_log_stream (filename)
 
 _find_caller ()
 
 log_first_n (lvl, msg, n=1, *name=None, key="caller")
 
 log_every_n (lvl, msg, n=1, *name=None)
 
 log_every_n_seconds (lvl, msg, n=1, *name=None)
 

Variables

 _LOG_COUNTER = Counter()
 
dict _LOG_TIMER = {}
 

Function Documentation

◆ _cached_log_stream()

fastreid.utils.logger._cached_log_stream ( filename)
protected

Definition at line 94 of file logger.py.

94def _cached_log_stream(filename):
95 return PathManager.open(filename, "a")
96
97
98"""
99Below are some other convenient logging methods.
100They are mainly adopted from
101https://github.com/abseil/abseil-py/blob/master/absl/logging/__init__.py
102"""
103
104

◆ _find_caller()

fastreid.utils.logger._find_caller ( )
protected
Returns:
    str: module name of the caller
    tuple: a hashable key to be used to identify different callers

Definition at line 105 of file logger.py.

105def _find_caller():
106 """
107 Returns:
108 str: module name of the caller
109 tuple: a hashable key to be used to identify different callers
110 """
111 frame = sys._getframe(2)
112 while frame:
113 code = frame.f_code
114 if os.path.join("utils", "logger.") not in code.co_filename:
115 mod_name = frame.f_globals["__name__"]
116 if mod_name == "__main__":
117 mod_name = "detectron2"
118 return mod_name, (code.co_filename, frame.f_lineno, code.co_name)
119 frame = frame.f_back
120
121

◆ log_every_n()

fastreid.utils.logger.log_every_n ( lvl,
msg,
n = 1,
* name = None )
Log once per n times.
Args:
    lvl (int): the logging level
    msg (str):
    n (int):
    name (str): name of the logger to use. Will use the caller's module by default.

Definition at line 160 of file logger.py.

160def log_every_n(lvl, msg, n=1, *, name=None):
161 """
162 Log once per n times.
163 Args:
164 lvl (int): the logging level
165 msg (str):
166 n (int):
167 name (str): name of the logger to use. Will use the caller's module by default.
168 """
169 caller_module, key = _find_caller()
170 _LOG_COUNTER[key] += 1
171 if n == 1 or _LOG_COUNTER[key] % n == 1:
172 logging.getLogger(name or caller_module).log(lvl, msg)
173
174

◆ log_every_n_seconds()

fastreid.utils.logger.log_every_n_seconds ( lvl,
msg,
n = 1,
* name = None )
Log no more than once per n seconds.
Args:
    lvl (int): the logging level
    msg (str):
    n (int):
    name (str): name of the logger to use. Will use the caller's module by default.

Definition at line 175 of file logger.py.

175def log_every_n_seconds(lvl, msg, n=1, *, name=None):
176 """
177 Log no more than once per n seconds.
178 Args:
179 lvl (int): the logging level
180 msg (str):
181 n (int):
182 name (str): name of the logger to use. Will use the caller's module by default.
183 """
184 caller_module, key = _find_caller()
185 last_logged = _LOG_TIMER.get(key, None)
186 current_time = time.time()
187 if last_logged is None or current_time - last_logged >= n:
188 logging.getLogger(name or caller_module).log(lvl, msg)
189 _LOG_TIMER[key] = current_time
190
191# def create_small_table(small_dict):
192# """
193# Create a small table using the keys of small_dict as headers. This is only
194# suitable for small dictionaries.
195# Args:
196# small_dict (dict): a result dictionary of only a few items.
197# Returns:
198# str: the table as a string.
199# """
200# keys, values = tuple(zip(*small_dict.items()))
201# table = tabulate(
202# [values],
203# headers=keys,
204# tablefmt="pipe",
205# floatfmt=".3f",
206# stralign="center",
207# numalign="center",
208# )
209# return table

◆ log_first_n()

fastreid.utils.logger.log_first_n ( lvl,
msg,
n = 1,
* name = None,
key = "caller" )
Log only for the first n times.
Args:
    lvl (int): the logging level
    msg (str):
    n (int):
    name (str): name of the logger to use. Will use the caller's module by default.
    key (str or tuple[str]): the string(s) can be one of "caller" or
        "message", which defines how to identify duplicated logs.
        For example, if called with `n=1, key="caller"`, this function
        will only log the first call from the same caller, regardless of
        the message content.
        If called with `n=1, key="message"`, this function will log the
        same content only once, even if they are called from different places.
        If called with `n=1, key=("caller", "message")`, this function
        will not log only if the same caller has logged the same message before.

Definition at line 126 of file logger.py.

126def log_first_n(lvl, msg, n=1, *, name=None, key="caller"):
127 """
128 Log only for the first n times.
129 Args:
130 lvl (int): the logging level
131 msg (str):
132 n (int):
133 name (str): name of the logger to use. Will use the caller's module by default.
134 key (str or tuple[str]): the string(s) can be one of "caller" or
135 "message", which defines how to identify duplicated logs.
136 For example, if called with `n=1, key="caller"`, this function
137 will only log the first call from the same caller, regardless of
138 the message content.
139 If called with `n=1, key="message"`, this function will log the
140 same content only once, even if they are called from different places.
141 If called with `n=1, key=("caller", "message")`, this function
142 will not log only if the same caller has logged the same message before.
143 """
144 if isinstance(key, str):
145 key = (key,)
146 assert len(key) > 0
147
148 caller_module, caller_key = _find_caller()
149 hash_key = ()
150 if "caller" in key:
151 hash_key = hash_key + caller_key
152 if "message" in key:
153 hash_key = hash_key + (msg,)
154
155 _LOG_COUNTER[hash_key] += 1
156 if _LOG_COUNTER[hash_key] <= n:
157 logging.getLogger(name or caller_module).log(lvl, msg)
158
159

◆ setup_logger()

fastreid.utils.logger.setup_logger ( output = None,
distributed_rank = 0,
* color = True,
name = "fastreid",
abbrev_name = None )
Args:
    output (str): a file name or a directory to save log. If None, will not save log file.
        If ends with ".txt" or ".log", assumed to be a file name.
        Otherwise, logs will be saved to `output/log.txt`.
    name (str): the root module name of this logger
    abbrev_name (str): an abbreviation of the module, to avoid long names in logs.
        Set to "" to not log the root module in logs.
        By default, will abbreviate "detectron2" to "d2" and leave other
        modules unchanged.

Definition at line 33 of file logger.py.

35):
36 """
37 Args:
38 output (str): a file name or a directory to save log. If None, will not save log file.
39 If ends with ".txt" or ".log", assumed to be a file name.
40 Otherwise, logs will be saved to `output/log.txt`.
41 name (str): the root module name of this logger
42 abbrev_name (str): an abbreviation of the module, to avoid long names in logs.
43 Set to "" to not log the root module in logs.
44 By default, will abbreviate "detectron2" to "d2" and leave other
45 modules unchanged.
46 """
47 logger = logging.getLogger(name)
48 logger.setLevel(logging.DEBUG)
49 logger.propagate = False
50
51 if abbrev_name is None:
52 abbrev_name = "d2" if name == "detectron2" else name
53
54 plain_formatter = logging.Formatter(
55 "[%(asctime)s] %(name)s %(levelname)s: %(message)s", datefmt="%m/%d %H:%M:%S"
56 )
57 # stdout logging: master only
58 if distributed_rank == 0:
59 ch = logging.StreamHandler(stream=sys.stdout)
60 ch.setLevel(logging.DEBUG)
61 if color:
62 formatter = _ColorfulFormatter(
63 colored("[%(asctime)s %(name)s]: ", "green") + "%(message)s",
64 datefmt="%m/%d %H:%M:%S",
65 root_name=name,
66 abbrev_name=str(abbrev_name),
67 )
68 else:
69 formatter = plain_formatter
70 ch.setFormatter(formatter)
71 logger.addHandler(ch)
72
73 # file logging: all workers
74 if output is not None:
75 if output.endswith(".txt") or output.endswith(".log"):
76 filename = output
77 else:
78 filename = os.path.join(output, "log.txt")
79 if distributed_rank > 0:
80 filename = filename + ".rank{}".format(distributed_rank)
81 PathManager.mkdirs(os.path.dirname(filename))
82
83 fh = logging.StreamHandler(_cached_log_stream(filename))
84 fh.setLevel(logging.DEBUG)
85 fh.setFormatter(plain_formatter)
86 logger.addHandler(fh)
87
88 return logger
89
90
91# cache the opened file object, so that different calls to `setup_logger`
92# with the same file name can safely write to the same file.
93@functools.lru_cache(maxsize=None)

Variable Documentation

◆ _LOG_COUNTER

fastreid.utils.logger._LOG_COUNTER = Counter()
protected

Definition at line 122 of file logger.py.

◆ _LOG_TIMER

dict fastreid.utils.logger._LOG_TIMER = {}
protected

Definition at line 123 of file logger.py.