|
| 1 | +import logging |
| 2 | +import os |
| 3 | + |
| 4 | +logger_initialized = {} |
| 5 | +global_log_file = [] |
| 6 | + |
| 7 | + |
| 8 | +def get_logger(name, log_file=None, log_level=logging.INFO): |
| 9 | + """Initialize and get a logger by name. |
| 10 | +
|
| 11 | + If the logger has not been initialized, this method will initialize the |
| 12 | + logger by adding one or two handlers, otherwise the initialized logger will |
| 13 | + be directly returned. During initialization, a StreamHandler will always be |
| 14 | + added. If `log_file` is specified and the process rank is 0, a FileHandler |
| 15 | + will also be added. |
| 16 | +
|
| 17 | + Args: |
| 18 | + name (str): Logger name. |
| 19 | + log_file (str | None): The log filename. If specified, a FileHandler |
| 20 | + will be added to the logger. |
| 21 | + log_level (int): The logger level. Note that only the process of |
| 22 | + rank 0 is affected, and other processes will set the level to |
| 23 | + "Error" thus be silent most of the time. |
| 24 | +
|
| 25 | + Returns: |
| 26 | + logging.Logger: The expected logger. |
| 27 | + """ |
| 28 | + logger = logging.getLogger(name) |
| 29 | + if name in logger_initialized: |
| 30 | + return logger |
| 31 | + # handle hierarchical names |
| 32 | + # e.g., logger "a" is initialized, then logger "a.b" will skip the |
| 33 | + # initialization since it is a child of "a". |
| 34 | + for logger_name in logger_initialized: |
| 35 | + if name.startswith(logger_name): |
| 36 | + return logger |
| 37 | + |
| 38 | + # stream_handler = logging.StreamHandler() |
| 39 | + # handlers = [stream_handler] |
| 40 | + handlers = [] |
| 41 | + |
| 42 | + rank = 0 |
| 43 | + |
| 44 | + if log_file is not None and len(global_log_file) == 0: |
| 45 | + log_path = os.path.dirname(log_file) |
| 46 | + if not os.path.exists(log_path): |
| 47 | + os.makedirs(log_path) |
| 48 | + |
| 49 | + global_log_file.append(log_file) |
| 50 | + |
| 51 | + if log_file is None and len(global_log_file) > 0: |
| 52 | + log_file = global_log_file[0] |
| 53 | + |
| 54 | + # only rank 0 will add a FileHandler |
| 55 | + if rank == 0 and log_file is not None: |
| 56 | + file_handler = logging.FileHandler(log_file, "a") |
| 57 | + handlers.append(file_handler) |
| 58 | + |
| 59 | + formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") |
| 60 | + for handler in handlers: |
| 61 | + handler.setFormatter(formatter) |
| 62 | + handler.setLevel(log_level) |
| 63 | + logger.addHandler(handler) |
| 64 | + |
| 65 | + if rank == 0: |
| 66 | + logger.setLevel(log_level) |
| 67 | + else: |
| 68 | + logger.setLevel(logging.ERROR) |
| 69 | + |
| 70 | + logger_initialized[name] = True |
| 71 | + |
| 72 | + return logger |
| 73 | + |
| 74 | + |
| 75 | +def PCHECK(expr, msg, *args): |
| 76 | + if not expr: |
| 77 | + get_logger("main").error(msg, *args) |
0 commit comments