| 151 | |
| 152 | |
| 153 | def _formatwarnmsg_impl(msg): |
| 154 | category = msg.category.__name__ |
| 155 | s = f"{msg.filename}:{msg.lineno}: {category}: {msg.message}\n" |
| 156 | |
| 157 | if msg.line is None: |
| 158 | try: |
| 159 | import linecache |
| 160 | line = linecache.getline(msg.filename, msg.lineno) |
| 161 | except Exception: |
| 162 | # When a warning is logged during Python shutdown, linecache |
| 163 | # and the import machinery don't work anymore |
| 164 | line = None |
| 165 | linecache = None |
| 166 | else: |
| 167 | line = msg.line |
| 168 | if line: |
| 169 | line = line.strip() |
| 170 | s += " %s\n" % line |
| 171 | |
| 172 | if msg.source is not None: |
| 173 | try: |
| 174 | import tracemalloc |
| 175 | # Logging a warning should not raise a new exception: |
| 176 | # catch Exception, not only ImportError and RecursionError. |
| 177 | except Exception: |
| 178 | # don't suggest to enable tracemalloc if it's not available |
| 179 | suggest_tracemalloc = False |
| 180 | tb = None |
| 181 | else: |
| 182 | try: |
| 183 | suggest_tracemalloc = not tracemalloc.is_tracing() |
| 184 | tb = tracemalloc.get_object_traceback(msg.source) |
| 185 | except Exception: |
| 186 | # When a warning is logged during Python shutdown, tracemalloc |
| 187 | # and the import machinery don't work anymore |
| 188 | suggest_tracemalloc = False |
| 189 | tb = None |
| 190 | |
| 191 | if tb is not None: |
| 192 | s += 'Object allocated at (most recent call last):\n' |
| 193 | for frame in tb: |
| 194 | s += (' File "%s", lineno %s\n' |
| 195 | % (frame.filename, frame.lineno)) |
| 196 | |
| 197 | try: |
| 198 | if linecache is not None: |
| 199 | line = linecache.getline(frame.filename, frame.lineno) |
| 200 | else: |
| 201 | line = None |
| 202 | except Exception: |
| 203 | line = None |
| 204 | if line: |
| 205 | line = line.strip() |
| 206 | s += ' %s\n' % line |
| 207 | elif suggest_tracemalloc: |
| 208 | s += (f'{category}: Enable tracemalloc to get the object ' |
| 209 | f'allocation traceback\n') |
| 210 | return s |