4

When using the Gurobi Python package (gurobipy v. 8.1.0) alongside the standard Python logging package, I get on console a doubled output for Gurobi, for example

Total elapsed time = 498.27s
[2019-03-04 17:51:58,804][INFO] Total elapsed time = 498.27s

Does anybody know how to remove logging for gurobipy? Thanks

user1403546
  • 1,680
  • 4
  • 22
  • 43

2 Answers2

1

I had this problem as well. Couldn't find an "official" solution so I rolled my own hack:

import sys

def solve():
    class DevNull:
        def write(self, *args, **kwargs):
            pass

        def flush(self, *args, **kwargs):
            pass

    sys.stdout = DevNull() 

    try:
        return _actually_solve()
    except Exception:
        # restore stdout so that handlers can print normally
        # https://docs.python.org/3/library/sys.html#sys.__stdout__ 
        sys.stdout = sys.__stdout__
        raise
    finally:
        sys.stdout = sys.__stdout__

This function wraps the actual solving logic in _actually_solve and replaces the standard output with a file-like object that ignores everything we write there.

BlackBear
  • 22,411
  • 10
  • 48
  • 86
1

The following worked for me. I put this code right after importing gurobipy

class GurobiFilter(logging.Filter):
    def __init__(self, name="GurobiFilter"):
        super().__init__(name)

    def filter(self, record):
        return False

grbfilter = GurobiFilter()

grblogger = logging.getLogger('gurobipy')
if grblogger is not None:
    grblogger.addFilter(grbfilter)
    grblogger = grblogger.getChild('gurobipy')
    if grblogger is not None:
        grblogger.addFilter(grbfilter)
Irv
  • 540
  • 4
  • 13