Safemotion Lib
Loading...
Searching...
No Matches
logger.py
Go to the documentation of this file.
1# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2import functools
3import logging
4import os
5import sys
6import time
7from collections import Counter
8from .file_io import PathManager
9from termcolor import colored
10
11
12class _ColorfulFormatter(logging.Formatter):
13 def __init__(self, *args, **kwargs):
14 self._root_name = kwargs.pop("root_name") + "."
15 self._abbrev_name = kwargs.pop("abbrev_name", "")
16 if len(self._abbrev_name):
17 self._abbrev_name = self._abbrev_name + "."
18 super(_ColorfulFormatter, self).__init__(*args, **kwargs)
19
20 def formatMessage(self, record):
21 record.name = record.name.replace(self._root_name, self._abbrev_name)
22 log = super(_ColorfulFormatter, self).formatMessage(record)
23 if record.levelno == logging.WARNING:
24 prefix = colored("WARNING", "red", attrs=["blink"])
25 elif record.levelno == logging.ERROR or record.levelno == logging.CRITICAL:
26 prefix = colored("ERROR", "red", attrs=["blink", "underline"])
27 else:
28 return log
29 return prefix + " " + log
30
31
32@functools.lru_cache() # so that calling setup_logger multiple times won't add many handlers
34 output=None, distributed_rank=0, *, color=True, name="fastreid", abbrev_name=None
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)
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
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
122_LOG_COUNTER = Counter()
123_LOG_TIMER = {}
124
125
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
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
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
__init__(self, *args, **kwargs)
Definition logger.py:13
setup_logger(output=None, distributed_rank=0, *color=True, name="fastreid", abbrev_name=None)
Definition logger.py:35
log_every_n_seconds(lvl, msg, n=1, *name=None)
Definition logger.py:175
log_every_n(lvl, msg, n=1, *name=None)
Definition logger.py:160
_cached_log_stream(filename)
Definition logger.py:94
log_first_n(lvl, msg, n=1, *name=None, key="caller")
Definition logger.py:126