In some applications, it is desirable to redirect Gurobi's LOG messages to a specific logging framework instead of using logging files or stdout. There are many different logging frameworks available for C#. The most commonly used abstraction layer is Microsoft.Extensions.Logging, for which extensive documentation is available. All major logging frameworks offer a provider that is compatible with this abstraction, as does Microsoft Azure.
Although Gurobi does not provide a direct link to this abstraction layer, it is relatively easy to use our callback mechanism for implementing this:
public class LoggerCallback : GRBCallback
{
private readonly ILogger _logger;
public LoggerCallback(ILogger logger)
{
_logger = logger;
}
protected override void Callback()
{
if (where == GRB.Callback.MESSAGE)
{
var msg = GetStringInfo(GRB.Callback.MSG_STRING);
if (msg != null)
{
var level = LogLevel.Information;
if (msg.StartsWith("Error"))
{
level = LogLevel.Error;
}
else if (msg.StartsWith("Warning"))
{
level = LogLevel.Warning;
}
_logger.Log(level, msg);
}
}
}
}
This class can be used as follows. Note how an instance of ILogger
is constructed and passed to our new LoggerCallback
class. All log information made available by Gurobi through the callback mechanism will be written to the ILogger
instance via its Log(level, msg)
method.
using Gurobi;
using Microsoft.Extensions.Logging;
var factory = LoggerFactory.Create(lb => lb.AddDebug());
var logger = factory.CreateLogger<Program>();
var env = new GRBEnv();
var model = new GRBModel(env);
model.AddVar(0, GRB.INFINITY, 1, GRB.CONTINUOUS, "X");
model.ModelSense = GRB.MINIMIZE;
model.SetCallback(new LoggerCallback(logger));
model.Optimize();
model.Dispose();
env.Dispose();
Comments
0 comments
Article is closed for comments.