GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — codeql/python/extractor/semmle/logging.py at codeql-cli/v2.27.2 · github/codeql Expand file tree/ Copy pathlogging.pyMore file actions 443 lines (372 loc) · 14.5 KB / Copy pathlogging.pyFile metadata and controls443 lines (372 loc) · 14.5 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 ''' Support for multi-process safe logging with colorized output. ''' import os import sys import traceback import multiprocessing import enum import datetime import platform from semmle.util import VERSION, get_analysis_version #Use standard Semmle logging levels OFF = 0 ERROR = 1 WARN = 2 INFO = 3 DEBUG = 4 TRACE = 5 TRACEBACK = 6 COLOR = 8 if os.name == "nt": MAGENTA = "" GREY = "" BLUE = "" YELLOW = "" RED = "" RESET = "" else: MAGENTA = "\x1b[35m" GREY = "\x1b[2m\x1b[37m" BLUE = "\x1b[34m" YELLOW = "\x1b[33m" RED = "\x1b[31m" RESET = '\x1b[0m' LOG_PREFIX = { TRACE: "[TRACE] ", DEBUG: "[DEBUG] ", INFO: "[INFO] ", WARN: "[WARN] ", ERROR: "[ERROR] ", TRACEBACK: "[TRACEBACK] ", COLOR | TRACE: GREY + "[TRACE] ", COLOR | DEBUG: "[DEBUG] ", COLOR | INFO: BLUE + "[INFO] ", COLOR | WARN: YELLOW + "[WARN] ", COLOR | ERROR: RED + "[ERROR] ", COLOR | TRACEBACK: MAGENTA + "[TRACEBACK] ", } def write_message(level, text): '''Write a message direct to stdout without queueing.''' reset = RESET if level & COLOR == COLOR else '' print(LOG_PREFIX[level] + text + reset) sys.stdout.flush() def write_message_with_proc(level, proc_id, text): reset = RESET if level & COLOR == COLOR else '' print(LOG_PREFIX[level] + proc_id + text + reset) sys.stdout.flush() _logging_process = None def format_message(fmt, args): '''Applies `%`-formatting to `fmt`, but only when there are arguments to interpolate. This mirrors the standard library's `logging` behaviour, and means that a message that has already been formatted -- and may therefore contain arbitrary `%` directives coming from the code being analysed -- is passed through unharmed.''' return fmt % args if args else fmt def stop(): _logging_process.join() class Logger(object): '''Multi-process safe logger''' def __init__(self, level=WARN, color=False): global _logging_process self.proc_id = "" self.level = level # macOS does not support `fork` properly, so we must use `spawn` instead. method = 'spawn' if sys.platform == "darwin" else None try: ctx = multiprocessing.get_context(method) except AttributeError: # `get_context` doesn't exist -- we must be running an old version of Python. ctx = multiprocessing self.queue = ctx.Queue() _logging_process = ctx.Process(target=_message_loop, args=(self.queue,)) _logging_process.start() self.color = COLOR if color else 0 def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() return False def set_process_id(self, proc_id): '''Set the process id to be included in log messages.''' self.proc_id = "[%d] " % proc_id def setLevel(self, level): self.level = level def log(self, level, fmt, *args): '''Log a message in a process safe fashion. Message will be of the form [level] fmt%args.''' if level <= self.level: txt = format_message(fmt, args) try: self.queue.put((self.color | level, self.proc_id, txt), False) except Exception: self.write_message(self.color | level, txt) def debug(self, fmt, *args): self.log(DEBUG, fmt, *args) def info(self, fmt, *args): self.log(INFO, fmt, *args) def warning(self, fmt, *args): self.log(WARN, fmt, *args) def error(self, fmt, *args): self.log(ERROR, fmt, *args) def trace(self, fmt, *args): self.log(TRACE, fmt, *args) def traceback(self, level=INFO): if level > self.level: return lines = trim_traceback(traceback.format_exc()) for line in lines: try: self.queue.put((self.color | TRACEBACK, self.proc_id, line), False) except Exception: self.write_message(TRACEBACK, line) def close(self): self.queue.put(None) def write_message(self, level, text): '''Write a message direct to stdout without queueing. Safe to use even after logger is closed. Calling this concurrently from different processes or before calling logger.close() may cause messages to become interleaved.''' if level <= self.level: write_message_with_proc(self.color | level, self.proc_id, text) #Function run by logger output process def _message_loop(log_queue): # use utf-8 as the character encoding for stdout/stderr to be able to properly # log/print things on systems that use bad default encodings (windows). sys.stdout.reconfigure(encoding='utf-8') sys.stderr.reconfigure(encoding='utf-8') common = set() while True: try: msg = log_queue.get() if msg is None: return level, proc_id, text = msg if proc_id: write_message_with_proc(level, proc_id, text) elif (level, text) not in common: write_message(level, text) common.add((level, text)) except KeyboardInterrupt: #Will be handled in other processes. pass def select_traceback_lines(lines, limit_start=30, limit_end=12): '''Select a subset of traceback lines to be displayed, cutting out the middle part of the traceback if the length exceeds `limit_start + limit_end`. This is intended to avoid displaying too many lines of tracebacks that are not relevant to the user.''' lines = lines.splitlines() num_lines = len(lines) limit = limit_start + limit_end if num_lines <= limit: yield from lines else: yield from lines[:limit_start] yield "... {} lines skipped".format(num_lines - limit) yield from lines[-limit_end:] def trim_traceback(lines): trimmed = [] for line in select_traceback_lines(lines): shortline = line.strip() try: if shortline.startswith("File"): shortline = '"semmle' + shortline.split("semmle")[-1] elif shortline.startswith("..."): pass else: continue except Exception: #Formatting error, just emit line as-is. pass trimmed.append(shortline) return trimmed class StructuredLogObject(object): """ Base class for CodeQL diagnostic message format see https://github.com/github/code-scanning/blob/main/docs/adrs/0035-diagnostics.md#codeql-diagnostic-message-format """ def to_dict(self): # Discard any entries with a value of `None` def f(v): if isinstance(v, StructuredLogObject): return v.to_dict() return v return {k: f(v) for k, v in self.__dict__.items() if v is not None} class Severity(StructuredLogObject, enum.Enum): ERROR = "error" WARNING = "warning" NOTE = "note" def to_dict(self): return self.value class Source(StructuredLogObject): def __init__(self, id, name, extractorName="python"): self.id = id self.name = name self.extractorName = extractorName def extractorName(self, extractorName): self.extractorName = extractorName return self class Visibility(StructuredLogObject): def __init__(self, statusPage=False, cliSummaryTable=False, telemetry=False): self.statusPage = statusPage self.cliSummaryTable = cliSummaryTable self.telemetry = telemetry def statusPage(self, statusPage): self.statusPage = statusPage return self def cliSummaryTable(self, cliSummaryTable): self.cliSummaryTable = cliSummaryTable return self def telemetry(self, telemetry): self.telemetry = telemetry return self class Location(StructuredLogObject): def __init__(self, file=None, startLine=None, startColumn=None, endLine=None, endColumn=None): self.file = file self.startLine = startLine self.startColumn = startColumn # If you set startline/startColumn you MUST also set endLine/endColumn, so we # ensure they are also set. self.endLine = endLine if endLine is None and startLine is not None: self.endLine = startLine self.endColumn = endColumn if endColumn is None and startColumn is not None: self.endColumn = startColumn def file(self, file): self.file = file return self def startLine(self, startLine): self.startLine = startLine return self def startColumn(self, startColumn): self.startColumn = startColumn return self def endLine(self, endLine): self.endLine = endLine return self def endColumn(self, endColumn): self.endColumn = endColumn return self class DiagnosticMessage(StructuredLogObject): def __init__(self, source, severity=Severity.WARNING, location=None, markdownMessage=None, plaintextMessage=None, helpLinks=None, visibility=None, attributes=None, timestamp=None): self.timestamp = timestamp or datetime.datetime.now().isoformat() self.source = source self.severity = severity self.location = location self.markdownMessage = markdownMessage self.plaintextMessage = plaintextMessage self.helpLinks = helpLinks if visibility is None: visibility = Visibility() self.visibility = visibility self.attributes = attributes def with_severity(self, severity): self.severity = severity return self def with_location(self, location): self.location = location return self def markdown(self, message): self.markdownMessage = message return self def text(self, message): self.plaintextMessage = message return self def help_link(self, link): if self.helpLinks is None: self.helpLinks = [] self.helpLinks.append(link) return self def cli_summary_table(self): self.visibility.cliSummaryTable = True return self def status_page(self): self.visibility.statusPage = True return self def telemetry(self): self.visibility.telemetry = True return self def attribute(self, key, value): if self.attributes is None: self.attributes = {} self.attributes[key] = value return self def with_timestamp(self, timestamp): self.timestamp = timestamp return self def extractor_telemetry_message(extractor_flags): return (DiagnosticMessage(Source("py/extractor/summary", "Python extractor telemetry"), Severity.NOTE) .markdown("Internal telemetry for the Python extractor.\n\nNo action needed.") .attribute("python_analysis_version", get_analysis_version()) .attribute("python_runtime_version", platform.python_version()) .attribute("extractor_version", VERSION) .attribute("extractor_flags", " ".join(extractor_flags) or "default") .telemetry() ) def parser_statistics_telemetry_message(old_parser_file_count, tree_sitter_parser_file_count): return (DiagnosticMessage(Source("py/extractor/parser-statistics", "Python parser statistics"), Severity.NOTE) .markdown("Internal parser telemetry for the Python extractor.\n\nNo action needed.") .attribute("old_parser_file_count", old_parser_file_count) .attribute("tree_sitter_parser_file_count", tree_sitter_parser_file_count) .telemetry() ) def get_stack_trace_lines(): """Creates a stack trace for inclusion into the `attributes` part of a diagnostic message. Limits the size of the stack trace to 5000 characters, so as to not make the SARIF file overly big. """ lines = trim_traceback(traceback.format_exc()) trace_length = 0 for i, line in enumerate(lines): trace_length += len(line) if trace_length > 5000: return lines[:i] return lines def _get_source_root(): """Get the source root directory for relativizing diagnostic paths.""" return os.environ.get("LGTM_SRC", os.getcwd()) def _relative_path(path): """Make a path relative to the source root for use in diagnostic locations. If the path is not under the source root, return it unchanged.""" source_root = os.path.abspath(_get_source_root()) abs_path = os.path.abspath(path) try: relpath = os.path.relpath(abs_path, source_root) except ValueError: # On Windows, relpath raises ValueError for paths on different drives return path if relpath.startswith(os.pardir): return path return relpath.replace(os.sep, "/") def syntax_error_message(exception, unit): diag_path = _relative_path(unit.path) l = Location(file=diag_path, startLine=exception.lineno, startColumn=exception.offset) error = (DiagnosticMessage(Source("py/diagnostics/syntax-error", "Could not process some files due to syntax errors"), Severity.WARNING) .with_location(l) .markdown("A parse error occurred while processing `{}`, and as a result this file could not be analyzed. Check the syntax of the file using the `python -m py_compile` command and correct any invalid syntax.".format(diag_path)) .attribute("traceback", get_stack_trace_lines()) .attribute("args", exception.args) .status_page() .cli_summary_table() .telemetry() ) return error def recursion_error_message(exception, unit): # if unit is a BuiltinModuleExtractable, there will be no path attribute l = Location(file=_relative_path(unit.path)) if hasattr(unit, "path") else None return (DiagnosticMessage(Source("py/diagnostics/recursion-error", "Recursion error in Python extractor"), Severity.ERROR) .with_location(l) .text(exception.args[0]) .attribute("traceback", get_stack_trace_lines()) .attribute("args", exception.args) .telemetry() ) def internal_error_message(exception, unit): # if unit is a BuiltinModuleExtractable, there will be no path attribute l = Location(file=_relative_path(unit.path)) if hasattr(unit, "path") else None return (DiagnosticMessage(Source("py/diagnostics/internal-error", "Internal error in Python extractor"), Severity.ERROR) .with_location(l) .text("Internal error") .attribute("traceback", get_stack_trace_lines()) .attribute("args", exception.args) .telemetry() ) |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |