%%c# log wrapper – homegrown

namespace LogWrapper
{
    ///

    /// strictly stateless  
    ///

    public class Log
    {
        private static readonly log4net.ILog log4n = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public const string FORMAT_BEGIN = ” vvv   {0}   vvv”;
        public const string FORMAT_CLOSE = ” ^^^   {0}   ^^^”;

        static Log()
        {
            //var fileInfo = new System.IO.FileInfo(PathFinder.APP_CONFIG);
            //if (!fileInfo.Exists) throw new Exception(“app.config not found”);
            //log4net.Config.XmlConfigurator.Configure(fileInfo);
        }
        ///

        /// This method conveniently logs to console, IDE output window and log4net
        ///

        ///
        public static void Info(Object o, int levels = 2, bool isStackTraceNeeded = false)
        {
            /*The thread id seen by log4net. According to MSDN:
             * An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host
             * can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host
             * can use the CLR Hosting API to schedule many managed threads against the same operating system thread,
             * or to move a managed thread between different operating system threads.
             */
            var winThrId = AppDomain.GetCurrentThreadId();
            var thId = “/T” + Thread.CurrentThread.ManagedThreadId + “/” + winThrId + “/ “;

            #region locator
            StackTrace stackTrace = new StackTrace(fNeedFileInfo: true);
            var frames = stackTrace.GetFrames();

            StringBuilder locator = new StringBuilder(StackFrameToStr(frames[1]));

            for (int i = 2; i <= levels; ++i)
            {
                if (frames.Length > i)
                {
                    locator.Append(“<-" + StackFrameToStr(frames[i]));
                }
            }

            //if (frames.Length > 2)locator.Append(“<-" + StackFrameToStr(frames[2]));

            var locator2 = “{” + locator.ToString().Trim() + “} “;
            var msg1 = o ?? “_nul_”;
            var msg2 = thId + locator2 + msg1;
            #endregion

            if (isStackTraceNeeded) msg2 += “n” + stackTrace;

            log4n.Info(msg2);
            //System.Diagnostics.Trace.Write(“Trace is possible as well.”);
            System.Diagnostics.Debug.WriteLine(msg2);
            Console.WriteLine(msg2);
            return;
        }
        public static void Error(Object o, int levels = 3)
        {
            Info(o, levels, isStackTraceNeeded: true);
        }

        public static void Crash(string msg, Exception fatalException = null)
        {
            string a = “System ought to crash. Unwise to catch this error : ” + msg;
            a += (fatalException == null) ? “” : “n–> Root Cause –> ” + fatalException.ToString();
            Log.Error(a);
            Environment.Exit(-99);
        }

        public static void LogClose(string name)
        {
            Info(string.Format(FORMAT_CLOSE, name));
        }

        public static void LogBegin(string name)
        {
            Info(string.Format(FORMAT_BEGIN, name));
        }
        ///

        /// http://stackoverflow.com/questions/2045935/is-there-anyway-to-programmably-flush-the-buffer-in-log4net
        ///

        public static void FlushBuffers()
        {
            foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
            {
                var buffered = appender as BufferingAppenderSkeleton;
                if (buffered != null) buffered.Flush();
            }
        }
        #region assertion tools
        public static void A(bool condition, string msg = “Programmer Error”, bool isFatal = false)
        {
            Assert(condition, msg, isFatal);
        }
        public static void Assert(bool condition, string msg = “Programmer Error”, bool isFatal = false)
        {
            if (!condition) Error(msg);
            Debug.Assert(condition, msg);
            if (!condition && isFatal) throw new Exception(“Fatal assertion failure.”);
        }
        #endregion

        #region private
        private static string StackFrameToStr(StackFrame f)
        {
            return Path.GetFileNameWithoutExtension(f.GetFileName()) + “.” + f.GetMethod().Name + “:” + f.GetFileLineNumber();
        }
        #endregion
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s