# Module `miplearn.log`

Expand source code

    #  MIPLearn: Extensible Framework for Learning-Enhanced Mixed-Integer Optimization
    #  Copyright (C) 2020, UChicago Argonne, LLC. All rights reserved.
    #  Released under the modified BSD license. See COPYING.md for more details.

    import logging
    import sys
    import time

    class TimeFormatter(logging.Formatter):
        def __init__(self, start_time, log_colors):
            super().__init__()
            self.start_time = start_time
            self.log_colors = log_colors

        def format(self, record):
            if record.levelno >= logging.ERROR:
                color = self.log_colors["red"]
            elif record.levelno >= logging.WARNING:
                color = self.log_colors["yellow"]
            else:
                color = self.log_colors["green"]
            return "%s[%12.3f]%s %s" % (
                color,
                record.created - self.start_time,
                self.log_colors["reset"],
                record.getMessage(),
            )

    def setup_logger(start_time=None, force_color=False):
        if start_time is None:
            start_time = time.time()
        if sys.stdout.isatty() or force_color:
            log_colors = {
                "green": "\033[92m",
                "yellow": "\033[93m",
                "red": "\033[91m",
                "reset": "\033[0m",
            }
        else:
            log_colors = {
                "green": "",
                "yellow": "",
                "red": "",
                "reset": "",
            }
        handler = logging.StreamHandler()
        handler.setFormatter(TimeFormatter(start_time, log_colors))
        logging.getLogger().addHandler(handler)
        logging.getLogger("miplearn").setLevel(logging.INFO)

## Functions

`def setup_logger(start_time=None, force_color=False)`
  Expand source code

      def setup_logger(start_time=None, force_color=False):
          if start_time is None:
              start_time = time.time()
          if sys.stdout.isatty() or force_color:
              log_colors = {
                  "green": "\033[92m",
                  "yellow": "\033[93m",
                  "red": "\033[91m",
                  "reset": "\033[0m",
              }
          else:
              log_colors = {
                  "green": "",
                  "yellow": "",
                  "red": "",
                  "reset": "",
              }
          handler = logging.StreamHandler()
          handler.setFormatter(TimeFormatter(start_time, log_colors))
          logging.getLogger().addHandler(handler)
          logging.getLogger("miplearn").setLevel(logging.INFO)

## Classes

`class TimeFormatter (start_time, log_colors)`

  Formatter instances are used to convert a LogRecord to text.

  Formatters need to know how a LogRecord is constructed. They are responsible for converting a LogRecord to (usually) a string which can be interpreted by either a human or an external system. The base Formatter allows a formatting string to be specified. If none is supplied, the the style-dependent default value, "%(message)s", "{message}", or "${message}", is used.

  The Formatter can be initialized with a format string which makes use of knowledge of the LogRecord attributes - e.g. the default value mentioned above makes use of the fact that the user's message and arguments are pre- formatted into a LogRecord's message attribute. Currently, the useful attributes in a LogRecord are described by:

  %(name)s Name of the logger (logging channel) %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL) %(levelname)s Text logging level for the message ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL") %(pathname)s Full pathname of the source file where the logging call was issued (if available) %(filename)s Filename portion of pathname %(module)s Module (name portion of filename) %(lineno)d Source line number where the logging call was issued (if available) %(funcName)s Function name %(created)f Time when the LogRecord was created (time.time() return value) %(asctime)s Textual time when the LogRecord was created %(msecs)d Millisecond portion of the creation time %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded (typically at application startup time) %(thread)d Thread ID (if available) %(threadName)s Thread name (if available) %(process)d Process ID (if available) %(message)s The result of record.getMessage(), computed just as the record is emitted

  Initialize the formatter with specified format strings.

  Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

  Use a style parameter of '%', '{' or '$' to specify that you want to use one of %-formatting, :meth:`str.format` (`{}`) formatting or :class:`string.Template` formatting in your format string.

  Changed in version: 3.2

  Added the `style` parameter.

  Expand source code

      class TimeFormatter(logging.Formatter):
          def __init__(self, start_time, log_colors):
              super().__init__()
              self.start_time = start_time
              self.log_colors = log_colors

          def format(self, record):
              if record.levelno >= logging.ERROR:
                  color = self.log_colors["red"]
              elif record.levelno >= logging.WARNING:
                  color = self.log_colors["yellow"]
              else:
                  color = self.log_colors["green"]
              return "%s[%12.3f]%s %s" % (
                  color,
                  record.created - self.start_time,
                  self.log_colors["reset"],
                  record.getMessage(),
              )

  ### Ancestors

  - logging.Formatter

  ### Methods

  `def format(self, record)`

    Format the specified record as text.

    The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

    Expand source code

        def format(self, record):
            if record.levelno >= logging.ERROR:
                color = self.log_colors["red"]
            elif record.levelno >= logging.WARNING:
                color = self.log_colors["yellow"]
            else:
                color = self.log_colors["green"]
            return "%s[%12.3f]%s %s" % (
                color,
                record.created - self.start_time,
                self.log_colors["reset"],
                record.getMessage(),
            )