This is a snippet code which is useful in creating your own logging class. You can compile this as a library and use it accross the projects.
using System;
using System.Configuration;
using System.Diagnostics;
using System.Reflection;
namespace MyLogging
{
    /// 
    /// provides event logging capabilities
    ///
    /// requires a LogSource setting in app/web.config, which must match the name of the event log
    ///  
    public class Logger
    {
        #region constants
        static readonly string ERROR_NOSOURCE = "MyLogging - cannot write to event log - please specify a LogSource in app/web.config";
        #endregion
        #region static ctor
        static Logger()
        {
            if (ConfigurationManager.AppSettings["LogSource"] == null)
            {
                throw new ApplicationException(ERROR_NOSOURCE);
            }
            else
            {
                _source = ConfigurationManager.AppSettings["LogSource"].ToString();
                if (!EventLog.SourceExists(_source))
                {
                    EventLog.CreateEventSource(_source, "Application");
                    EventLog.WriteEntry(_source, "log source created");
                }
            }
        }
        #endregion
        #region properties - LogSource
        private static string _source = null;
        public static string LogSource
        {
            get { return _source; }
            set { _source = value; }
        }
        #endregion
        #region public logging methods
        /// 
        /// logs an exception, using reflection to determine calling method and module
        ///  
        /// 
        public static void LogException(Exception ex)
        {
            MethodBase  method = ex.TargetSite;
            Module      module = method.Module;
            string      msg = module.Name + "." + method.Name
                            + " - " + ex.Message
                            + Environment.NewLine
                            + "Stack Trace - " + ex.StackTrace;
            LogMessage(msg, EventLogEntryType.Error);
        }
        /// 
        /// logs a (non-error) message
        ///  
        /// 
        public static void LogMessage(string message)
        {
            LogMessage(message, EventLogEntryType.Information);
        }
        /// 
        /// logs a message, with specified EventLogEntryType
        ///  
        /// 
        /// 
        private static void LogMessage(string message, EventLogEntryType type)
        {
            message = Assembly.GetExecutingAssembly().FullName + " - " + message;
            //if (_source == null)
            //{
            //    throw new ApplicationException(ERROR_NOSOURCE);
            //}
            EventLog.WriteEntry(_source, message, type);
        }
        #endregion
    }
}
								
			
Leave a Reply