I am currently using cvxpy
for my project. When I solve an optimization problem, I have the option to turn the verbose flag on using prob.solve(solver=cvx.CVXOPT, verbose=True)
. When I do that, the logger starts printing the DEBUG level log messages to the console.
I understand that it is because of the following section in cvxpy
source code.
LOGGER = logging.getLogger("__cvxpy__")
LOGGER.propagate = False
LOGGER.setLevel(logging.INFO)
_stream_handler = logging.StreamHandler(sys.stdout)
_stream_handler.setLevel(logging.INFO)
_formatter = logging.Formatter(
fmt="(CVXPY) %(asctime)s: %(message)s", datefmt="%b %d %I:%M:%S %p"
)
_stream_handler.setFormatter(_formatter)
LOGGER.addHandler(_stream_handler)
How do I redirect the messages to a file without hacking the original source code? Can there be a setter method? TIA
cvxpy doesn't supply any direct option to print log to a file, but rather it uses sys.stdout
.
You can, however, redirect sys.stdout
into a file instead of the console. To do that see: Redirect stdout to a file in Python? or Temporarily Redirect stdout/stderr for example.
You redirect output into a file in your program right before the .solve()
call, and it should print the log into a file. The easiest way is with contextlib.redirect_stdout
That way when you call to solve
with verbose=True
, the sys.stdout
that mentioned in the block of code you mentioned will redirect to a file instead of the console. If you're not familiar with stdin, stdout and stderr I would recommend to have a quick read about them first.