syslog4net.Layout.SyslogLayout.Format C# (CSharp) Method

Format() public method

Formats data within the event and writes the formatted data out to the provided writer instance
public Format ( TextWriter writer, log4net.Core.LoggingEvent logEvent ) : void
writer System.IO.TextWriter writer to output the formatted data to
logEvent log4net.Core.LoggingEvent logging event data to use
return void
        public override void Format(TextWriter writer, LoggingEvent logEvent)
        {
            logEvent.Properties["log4net:StructuredDataPrefix"] = StructuredDataPrefix;

            using (var stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                this._layout.Format(stringWriter, logEvent);

                // truncate the message to SYSLOG_MAX_MESSAGE_LENGTH or fewer bytes
                string message = stringWriter.ToString();

                var utf8 = Encoding.UTF8;

                byte[] utfBytes = utf8.GetBytes(message);
                int lMaxMessageLength = Convert.ToInt32(this.MaxMessageLength);
                if (utfBytes.Length > lMaxMessageLength)
                {
                    message = utf8.GetString(utfBytes, 0, lMaxMessageLength);
                }

                writer.Write(message);
            }
        }

Usage Example

Example #1
0
        public void TestFormat()
        {
            SyslogLayout layout = new SyslogLayout();
            layout.StructuredDataPrefix = "TEST@12345";
            layout.ActivateOptions();

            var exception = new Exception("test exception message");
            ILoggerRepository logRepository = Substitute.For<ILoggerRepository>();
            var evt = new LoggingEvent(typeof(SyslogLayoutTests), logRepository, "test logger", Level.Debug, "test message", exception);

            StringWriter writer = new StringWriter();

            layout.Format(writer, evt);

            string result = writer.ToString();

            // it's hard to test the whole message, because it depends on your machine name, process id, time & date, etc.
            // just test the message's invariant portions
            Assert.IsTrue(result.StartsWith("<135>1 "));
            Assert.IsTrue(result.Contains("[TEST@12345 EventSeverity=\"DEBUG\" ExceptionType=\"System.Exception\" ExceptionMessage=\"test exception message\"]"));
            Assert.IsTrue(result.EndsWith("test message" + Environment.NewLine));
        }
All Usage Examples Of syslog4net.Layout.SyslogLayout::Format