Serilog.Formatting.Display.MessageTemplateTextFormatter.Format C# (CSharp) Method

Format() public method

Format the log event into the output.
public Format ( LogEvent logEvent, TextWriter output ) : void
logEvent Serilog.Events.LogEvent The event to format.
output System.IO.TextWriter The output.
return void
        public void Format(LogEvent logEvent, TextWriter output)
        {
            if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
            if (output == null) throw new ArgumentNullException(nameof(output));

            // This could be lazier: the output properties include
            // everything from the log event, but often we won't need any more than
            // just the standard timestamp/message etc.
            var outputProperties = OutputProperties.GetOutputProperties(logEvent);

            foreach (var token in _outputTemplate.Tokens)
            {
                var pt = token as PropertyToken;
                if (pt == null)
                {
                    token.Render(outputProperties, output, _formatProvider);
                    continue;
                }

                // First variation from normal rendering - if a property is missing,
                // don't render anything (message templates render the raw token here).
                LogEventPropertyValue propertyValue;
                if (!outputProperties.TryGetValue(pt.PropertyName, out propertyValue))
                    continue;

                // Second variation; if the value is a scalar string, use literal
                // rendering and support some additional formats: 'u' for uppercase
                // and 'w' for lowercase.
                var sv = propertyValue as ScalarValue;
                if (sv != null && sv.Value is string)
                {
                    var overridden = new Dictionary<string, LogEventPropertyValue>
                    {
                        { pt.PropertyName, new LiteralStringValue((string) sv.Value) }
                    };

                    token.Render(overridden, output, _formatProvider);
                }
                else
                {
                    token.Render(outputProperties, output, _formatProvider);
                }
            }
        }

Usage Example

 public void LowercaseFormatSpecifierIsSupportedForStrings()
 {
     var formatter = new MessageTemplateTextFormatter("{Name:w}", CultureInfo.InvariantCulture);
     var evt = DelegatingSink.GetLogEvent(l => l.Information("{Name}", "Nick"));
     var sw = new StringWriter();
     formatter.Format(evt, sw);
     Assert.AreEqual("nick", sw.ToString());
 }
All Usage Examples Of Serilog.Formatting.Display.MessageTemplateTextFormatter::Format
MessageTemplateTextFormatter