In this post, I provide a simple sample of how to use the Enterprise Library for trace logging.
Ensure that you add a reference to Enterprise Logging Application Block to your project, if this is not showing up, you probably don't have the Enterprise Library installed.
Sample Code:
A few things to note:using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using Microsoft.Practices.EnterpriseLibrary.Logging; using System.IO; namespace ELSample { class Program { static void Main(string[] args) { string file = @"c:\myfile.txt"; try { WriteLogEntry("Trace",string.Format("Start to read file {0}.", file)); using (StreamReader sr = new StreamReader(file)) { //do something here. } WriteLogEntry("Trace", string.Format("Finished reading file {0}.", file)); } catch (Exception ex) { WriteLogEntry("Error", "Exception Occurred."); WriteLogEntry("Error", string.Format("Source: {0}.", ex.Source)); WriteLogEntry("Error", string.Format("Type: {0}.", ex.GetType())); WriteLogEntry("Error", string.Format("Message: {0}.", ex.Message)); if (ex.InnerException != null) { WriteLogEntry("Error", string.Format("Inner Exception: {0}.", ex.InnerException.Message)); } } } /// <summary> /// Write a log entry using the Enterprise Library /// </summary> /// <param name="LogCategory">This is the name of the Trace Listener, e.g. Trace, Error</param> /// <param name="LogMessage">Log Entry to write</param> public static void WriteLogEntry(string LogCategory, string LogMessage) { LogEntry entry = new LogEntry(); entry.Categories.Add(LogCategory); entry.Message = LogMessage; StackTrace trace = new StackTrace(); entry.Title = string.Format("{0}.{1}", trace.GetFrame(1).GetMethod().ReflectedType.Name, trace.GetFrame(1).GetMethod().Name); Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(entry); } } }
- I know that the sample is not from a plug-in.
- Same config section, the logging part, as in the first post.
- If you turn a trace listener off, the WriteLogEntry method will not write any entries, but there will be some processing done, so it will run slower than without it, as with everything in life it's a trade off.
- It probably makes sense to have a separate method for logging exceptions.
- I normally only bother with two trace listeners, Trace and Error. The former is normally equivalent to Verbose logging, the latter to ... Error logging.
What's about NLog, Log4net, Common.Logging, Serilog, etc ?
ReplyDeleteThis post is about the enterprise library so it doesn't include any information about NLog, log4net, etc...
Delete