Log4net's new TelnetAppender
The recently released 1.2.9-beta of log4net contains a new appender -- TelnetAppender. This appender acts like a telnet server and allows telnet clients to connect to it and monitor log4net's trace messages. I've only used log4net 1.2.8 but the TelnetAppender sounded pretty neat so I had to try it out. Here's a quick sample app I did. Note the DOMConfigurator has been deprecated and I'm now using the XmlConfigurator:
Option Strict On Option Explicit On Imports System.IO Imports System.Reflection Imports log4net Imports log4net.Config Public Class Module1 Shared Sub Main() XmlConfigurator.Configure(New FileInfo("logging.xml")) Console.WriteLine("Logging configured. Start up a telnet client and press Enter to continue...") Console.ReadLine() Dim w As New Worker w.Foo1() End Sub End Class Public Class Worker Public Shared ReadOnly m_logger As ILog = LogManager.GetLogger(GetType(Worker)) Public Sub Foo1() m_logger.Debug("Enter " & LogUtility.MethodName()) Bar1(34) m_logger.Debug("Exit " & LogUtility.MethodName()) End Sub Public Function Bar1(ByVal val As Integer) As Integer m_logger.Debug("Enter " & LogUtility.MethodName() & " with val = " & val.ToString()) Dim result As Integer = val * 7 m_logger.Debug("Leaving " & LogUtility.MethodName() & " with: " & result) Return result End Function End Class Public Class LogUtility Public Shared Function MethodName() As String ' back up one stack frame to get the caller's method name Dim sf As StackFrame = New StackFrame(1) Dim mb As MethodBase = sf.GetMethod() Return String.Format("{0}.{1}", mb.ReflectedType.ToString(), mb.Name) End Function End Class
Here's my log4net config file (logging.xml):
<?xml version="1.0" encoding="utf-8" ?> <log4net> <appender name="ods" type="log4net.Appender.OutputDebugStringAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%-5p [%t]: %m%n" /> </layout> </appender> <appender name="tnet" type="log4net.Appender.TelnetAppender"> <port value="23" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%-5p [%t]: %m%n" /> </layout> </appender> <root> <level value="ALL" /> <appender-ref ref="ods" /> <appender-ref ref="tnet" /> </root> </log4net>
Obviously the TelnetAppender is designed for a process that is always running (like a Windows Service). Since this is just a simple console demo, I added a pause right after log4net is initialized to give you a chance to start up a telnet client and connect to your local machine. You should get a message like:
TelnetAppender v1.0 (1 active connections)
At this point, go back to the demo and press Enter. The log4net messages will be streamed to your telnet client. Too fun!