LogEventInfo logEvent = new LogEventInfo(LogLevel.Debug, "MyLogger", "Log message"); if (logEvent.TryGetCachedLayoutValue("formattedMessage", out var formattedMessage)) { Console.WriteLine("Formatted message: " + formattedMessage.ToString()); }
string layoutString = "${date}|${level:uppercase=true}|${message}"; Layout layout = Layout.FromString(layoutString); LogEventInfo logEvent = new LogEventInfo(LogLevel.Debug, "MyLogger", "Log message"); logEvent.Layout = layout; string formattedMessage = logEvent.FormattedMessage; if (logEvent.TryGetCachedLayoutValue("formattedMessage", out var cachedValue)) { Console.WriteLine("Cached formatted message: " + cachedValue.ToString()); }In this example, a custom Layout object is created by parsing a string. Then, a LogEventInfo object is created and the Layout object is set. The FormattedMessage property is accessed to evaluate the layout. After that, the TryGetCachedLayoutValue() method is invoked to retrieve the cached value of the FormattedMessage. Overall, the LogEventInfo.TryGetCachedLayoutValue method is a useful feature provided by the NLog package library for speedy logging in C#.