How to use Log4net TelnetAppender and Trace Listeners


A

anonieko

Is there a way to use Log4net and Trace Listeners?








AssembyInfo.cs
-----------------------

// This tells Log4Net to look for a Log4Net.config file in the
execution directory,
// in this case, the webroot. This file contains Log4Net configuration
settings.
[assembly:log4net.Config.XmlConfigurator(ConfigFile="Log4Net.config",Watch=true)]




log4net.config
--------------------



<?xml version="1.0" encoding="utf-8" ?>
<log4net>

<appender name="tnet" type="log4net.Appender.TelnetAppender">
<port value="49232" />
<layout type="log4net.Layout.PatternLayout">
<!--
<conversionPattern value="%-5p [%t]: %m%n" />
-->
<conversionPattern value="%m%n" />
</layout>
</appender>

<root>
<level value="ALL" />
<appender-ref ref="tnet" />
</root>
</log4net>


-----In your program, include the namespace

using log4net;

namespace Riag.Applications.Common
{


public sealed class Tracer
{
private static readonly ILog Log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);


public static void WriteError( string msg )
{
string prefix = LogLinePrefix() + " ERROR";
Trace.WriteLineIf(_appSwitch.TraceError, msg, prefix );
Log.Error( prefix+ ": " + msg);
}

etc

=====
Entire source


//---------------------------------------------------------------
// 2003-09-01 ERV Initial Version
// 2005-02-15 ERV Improve the creation of textwriter files.


using System;
using System.Diagnostics;
using System.Configuration;
using System.IO;
using System.Reflection;
using log4net;

namespace Riag.Applications.Common
{
/// <summary>
/// Provides tracing for applications using System.Diagnotics
classes.
/// <para>= (2003).</para>
/// </summary>
/// <remarks>
/// <para>
/// Tracer will perform custom trace output specified in
/// the applications Configuration Settings. Specifically
/// designed for console applications. Tracer makes trace log
/// ouputs uniform as much as possible. This class can not be
instantiated.
/// </para>
/// <para>
/// Here is a sample code:
/// </para>
/// <code>
/// // Sample Setup Logger for Console App. Option 1
///
/// string LogDirectory =
Utility.GetConfigurationAppSettings("LogDirectory");
/// string TraceOutputs =
Utility.GetConfigurationAppSettings("TraceOutputs");
/// Tracer.Initialize( TraceOutputs, LogDirectory );
///
/// // Sample Setup Logger for Console App. Option 1
/// Tracer.DefaultInitialize(null);
///
/// // Setup Logger for We application page
/// // 'this' is a reference to a Page object
/// Tracer.DefaultInitialize(this);
/// </code>
///
/// Here is a sample .config entry:
/// <code>
/// &lt;configuration&gt;
/// &lt;appSettings&gt;
/// &lt;add key="LogDirectory" value="logs/" /&gt;
/// &lt;add key="TraceOutputs" value="test1.txt" /&gt;
/// &lt;/appSettings&gt;
/// &lt;system.diagnostics&gt;
/// &lt;switches&gt;
/// &lt;add name="app" value="4" /&gt;
/// &lt;/switches&gt;
/// &lt;/system.diagnostics&gt;
/// &lt;/configuration&gt;
/// </code>
/// </remarks>
public sealed class Tracer
{
private static readonly ILog Log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

private Tracer() {}

/// <summary>
/// The private applications trace switch. This should be
initialized
/// during application start.
/// </summary>
private static TraceSwitch _appSwitch;

/// <summary>Empty constructor</summary>
/// <summary>The public trace swith property</summary>
public static TraceSwitch AppSwitch
{
get { return _appSwitch; }
}


enum Duration
{
Daily,
Weekly,
Monthly
}


/// <summary>Initialize with the default formatting of yyMMdd_,
and weekly interval</summary>
public static void Initialize(string traceListeners, string
logDir )
{
Initialize( traceListeners, logDir, "yyMMdd_",
Tracer.Duration.Weekly); // using fix params for now
}

/// <summary>Tracer initialization method</summary>
/// <remarks>
/// Set the built-in Trace object to a specified listener
/// which can be combination of the following: console,
/// eventlog, or a trace file. Trace file are named,
/// YYMMDD_filename.txt.
/// </remarks>
/// <param name="traceListeners">Comma separated list of
listeners</param>
/// <param name="logDir">Absolute path of log directory</param>
/// <param name="filePrefixDatePattern"></param>
/// <param name="duration"></param>
private static void Initialize(string traceListeners, string
logDir, string filePrefixDatePattern , Tracer.Duration duration )
{
// PUT SOMETHING LIKE THIS IN YOUR .CONFIG FILE
//
// <?xml version="1.0" encoding="utf-8" ?>
// <configuration>
// <appSettings>
// <add key="LogDirectory" value="logs/" />
// <add key="TraceOutputs" value="CardW.txt" />
// </appSettings>
// <system.diagnostics>
// <switches>
// <add name="app" value="4" />
// </switches>
// </system.diagnostics>
// </configuration>

_appSwitch = new TraceSwitch("app", "Entire Application");

Trace.IndentSize = 2;
Trace.AutoFlush = true;
string listenersString = traceListeners;
string directoryString = logDir; // this must be an absolute
path.



if ( directoryString.Trim().Length != 0 )
directoryString = Utility.AdjustDirPath(directoryString);
// make sure it ends with

string[] arrListeners = listenersString.Split(',');

if ( arrListeners != null )
{
// Add each to the Trace objects's listeners
foreach ( string listener in arrListeners )
{
if ( listener.Trim().ToLower() == "console" )
{
Trace.Listeners.Add(new
TextWriterTraceListener(Console.Out));

}
else if ( listener.Trim().ToLower() == "eventlog" )
{
Trace.Listeners.Add( new EventLogTraceListener());

}

else
{
// Ok. Interpret the listener string as a filename
suffix for a text log.
//
try
{
// Try to create the log directory
//
if ( ! Directory.Exists( directoryString) )
{
Directory.CreateDirectory( directoryString);
}

if ( Directory.Exists( directoryString) )
{

DateTime weekEnd = GetEndingDay(DateTime.Now,
duration);
string listenerPadded =
weekEnd.ToString(filePrefixDatePattern )
+ listener.Trim();

AddTextWriterListener( directoryString +
listenerPadded );
}
}
catch(Exception excp)
{
string errorMsg = "ERROR: Unable to Create Trace
to " + listener + "-" + excp.Message;

// last resort
Flush2File("c:\\Tracer.Err.txt" , errorMsg, true);
}
}

}

}
}

/// <summary>
/// Write append to a text file
/// </summary>
/// <param name="file"></param>
/// <param name="msg"></param>
/// <param name="append"></param>
public static void Flush2File(string file, string msg, bool
append)
{
try
{
using ( StreamWriter sw = new StreamWriter(file, append) )
{
sw.Write( msg);

sw.Close();
}

}
catch
{
throw;
}
}


/// <summary>
/// Returns the date of the next Sunday from a given date.
/// </summary>
/// <param name="dt">Starting date</param>
/// <param name="duration"></param>
/// <returns></returns>
private static DateTime GetEndingDay ( DateTime dt, Duration
duration)
{
switch( duration )
{
case Duration.Weekly:
while (dt.DayOfWeek != System.DayOfWeek.Sunday )
{
dt = dt.AddDays(1);
}
break;

}

return dt;
}

/// <summary/>
public static void DefaultInitialize(object logObject)
{
// Initialize log system
string logDirectory =
Utility.GetConfigurationAppSettings("LogDirectory");
string traceOutputs =
Utility.GetConfigurationAppSettings("TraceOutputs");

// Convert into absolute path if coming from a page object
(i.e. web app)
System.Web.UI.Page page = logObject as System.Web.UI.Page;
if ( page != null)
{
if ( ! Path.IsPathRooted( logDirectory) )
{
logDirectory = page.Server.MapPath(logDirectory);
}
}

Tracer.Initialize( traceOutputs, logDirectory);
}

#region public Write Functions
/// <summary>
/// Writes error message to Trace.
/// </summary>
/// <param name="msg"></param>
public static void WriteError( string msg )
{
string prefix = LogLinePrefix() + " ERROR";
Trace.WriteLineIf(_appSwitch.TraceError, msg, prefix );
Log.Error( prefix+ ": " + msg);
}
/// <summary>
///
/// </summary>
/// <param name="format"></param>
/// <param name="args"></param>
public static void WriteError( string format, params object[]
args)
{
WriteError(System.String.Format(format, args));
}
/// <summary>
/// Writes warning message to Trace.
/// </summary>
/// <param name="msg"></param>
public static void WriteWarning( string msg )
{
string prefix = LogLinePrefix() + " WARN";
Trace.WriteLineIf(_appSwitch.TraceWarning, msg, prefix );
Log.Warn( prefix+ ": " + msg);
}
/// <summary>
///
/// </summary>
/// <param name="format"></param>
/// <param name="args"></param>
public static void WriteWarning( string format, params object[]
args)
{
WriteWarning(System.String.Format(format, args));
}
/// <summary>
/// Write Informational message to Trace.
/// </summary>
/// <param name="msg"></param>
public static void WriteInfo( string msg )
{
string prefix = LogLinePrefix() + " INFO";
Trace.WriteLineIf(_appSwitch.TraceInfo, msg, prefix );
Log.Info( prefix+ ": " + msg);
}
/// <summary>
///
/// </summary>
/// <param name="format"></param>
/// <param name="args"></param>
public static void WriteInfo( string format, params object[]
args)
{
WriteInfo(System.String.Format(format, args));
}
/// <summary>
/// Write verbose message to Trace.
/// </summary>
/// <param name="msg"></param>
public static void WriteVerbose( string msg )
{
string prefix = LogLinePrefix() + " VERB";
Trace.WriteLineIf(_appSwitch.TraceVerbose, msg, prefix );
Log.Debug( prefix+ ": " + msg);
}
/// <summary>
///
/// </summary>
/// <param name="format"></param>
/// <param name="args"></param>
public static void WriteVerbose( string format, params object[]
args)
{
WriteVerbose(System.String.Format(format, args));
}
/// <summary>
/// Writes debug message to Debug object.
/// </summary>
/// <param name="msg"></param>
public static void WriteDebug( string msg )
{
string prefix = LogLinePrefix() + " DEBUG";
Debug.WriteLineIf(_appSwitch.TraceVerbose, msg, prefix );
Log.Debug( prefix+ ": " + msg);
}
/// <summary>
///
/// </summary>
/// <param name="format"></param>
/// <param name="args"></param>
public static void WriteDebug( string format, params object[]
args)
{
WriteDebug(System.String.Format(format, args));
}

private static string LogLinePrefix()
{
return DateTime.Now.ToString( "yy/MM/dd HH:mm:ss:fff") + "["
+ Environment.MachineName + "]" ;
}

#endregion


#region Helper Methods

// This method is a safe way to add a TextWriterListener to the
// Trace.Listeners collection. It ensures that only 1
// TextWriterTraceListener is active at a time. If it detects
that
// the object exists, it will not add. If filename changes, it
will
// close all TextWriterTraceListeners, and add the new one.
private static bool AddTextWriterListener( string
fullPathFilename)
{
bool returnValue = false;

// this will safely cast object to a type becaue it return
null if not compatible.
TextWriterTraceListener currTextWriter =
Trace.Listeners[fullPathFilename] as TextWriterTraceListener;

if ( currTextWriter == null)
{
// The listner is not yet in the list. It maybe a different
filename
// or new filename. We should then close and remove all
TextWriterTraceListeners
// from TraceListeners.
RemoveTextWriterListeners();

// Add the new listener
Trace.Listeners.Add( new
TextWriterTraceListener(fullPathFilename, fullPathFilename));

returnValue = true;
}

return returnValue;
}

// Iterate through the built-in Trace.Listeners collection
// and remove the TextWriterTraceListener objects. Be sure
// to close the object first.
private static void RemoveTextWriterListeners()
{
foreach( object l in Trace.Listeners)
{
TextWriterTraceListener aListener = l as
TextWriterTraceListener;
if ( aListener != null )
{
aListener.Close();
Trace.Listeners.Remove(aListener);
}
}
}

#endregion

}
}

#region Junks
//
//#region The Singleton Pattern in C#
//
//private static volatile Tracer instance;
//private static object syncRoot = new Object();
//
//
// /// <summary>
// ///
// /// </summary>
//public static Tracer Instance
//{
//get
//{
//if (instance == null)
//{
//lock (syncRoot)
//{
//if (instance == null)
//instance = new Tracer();
//}
//}
//
//return instance;
//}
//}
//#endregion
#endregion
 
Ad

Advertisements

A

anonieko

This is a very practical guide to start using log4net quickly. Log4net
is the most common and standard tool to be used to log C# applications.
This tool can write logs in log files, database log table or xml files.
(There is some other ways to write logs too)


1- Download log4net from http://logging.apache.org/log4net/
2- In Visual Studio->WebSite->AddReference add a new reference do
log4net.dll that you downloaded.
3- Put this in the beginning of web.config file:
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections> ...

4- Now put this in the end of web.config file:

<log4net>
<logger name="default">
<level value="DEBUG"/>
</logger>
<root>
<level value="WARN" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender"
type="log4net.Appender.RollingFileAppender" >
<param name="File" value="log/log.txt" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p
%d{yyyy-MM-dd hh:mm:ss} - %m%n" />
</layout>
</appender>
</log4net>

this configuration creates a log file in ~/log/log.txt.

5- To use log4net put this as a local class variable:
protected static readonly ILog log =
LogManager.GetLogger("default");

6- And do this to write messages in the log file.
log.Debug("this text will be in log file");

7- A very good program to read log files is called BareTail, you can
find it easily.
8- This is an example class - Example.cs
9- This is all you need to start using log4net
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top