Getting formatted output of ILogger.Log for other destination

42 Views Asked by At

The widely-recommended pattern is to always allow ILogger to format its messages rather than passing it a pre-formatted string. CA2254 even chastises you if you don't. In a UI application, there are often cases where we want to log a message to the UI as well as the log. An error dialog would be simple (ugly) example. In that case, it would be tempting to do something like:

string message = $"Exception while doing a thing. Code={ex.Code}, {ex.Message}";
_logger.LogError(message);
Dialog.Open(Icon.Error, message);

That breaks the pattern. Other than constant repetition/duplication of code, is there a good terse way to define the message in a logger-friendly way and get immediate access to the formatted result for use in the same context as the original Log invocation? To be clear, I'm not talking about monitoring the stream of messages elsewhere and funneling them all to a list on the UI. For example, is there a way to get to code like this, maintaining the normal efficiencies of loggers?

LogMessage message = new(LogLevel.Error, "Exception while doing a thing. Code={ex.Code}, {ex.Message}", ex.Code, ex.Message);
_logger.Log(message);
Dialog.Open(Icon.Error, message.ToString());
0

There are 0 best solutions below