Intuitive interfaces, amazing user experience, rock-solid back end, agile delivery, exceptional testing, features people will love, user-centric design

Logging in .NET using extension methods

30/December / 2011

Here is something that we use with every .NET project. A simple set of logging extension methods, extremely easy to call, can be used in ASP.NET, SharePoint or Dynamics projects.

            List dummyList = new List();
            dummyList.Add("test 1");
            dummyList.Add("test 2");
            dummyList.Add("test 3");

            dummyList.Log();
        public static void Log(this T item)
        {
            item.Log(string.Empty, EventLogEntryType.Information, 0);
        }

        public static void Log(this T item, int depth)
        {
            item.Log(string.Empty, EventLogEntryType.Information, depth);
        }

        public static void Log(this T item, string category, int depth)
        {
            item.Log(category, EventLogEntryType.Information, depth);
        }

        public static void Log(this T item, string category, EventLogEntryType eventLogEntryType)
        {
            item.Log(category, eventLogEntryType, 0);
        }

        public static void Log(this T item, EventLogEntryType eventLogEntryType, int depth)
        {
            item.Log(string.Empty, eventLogEntryType, depth);
        }

        public static void Log(this T item, string category, EventLogEntryType eventLogEntryType, int depth)
        {
            if (item != null)
            {
                bool isException = false;
                string logContent = string.Empty;

                logContent += System.Environment.NewLine;
                logContent += GetFullyQualifiedContextName();
                logContent += System.Environment.NewLine;

                #region Log content
                if (item is Exception)
                {
                    // Treat exception in a slightly different way
                    Exception ex = item as Exception;
                    if (ex != null)
                    {
                        isException = true;
                        logContent += ex.GetExceptionDetails();
                        category = "MyAppException";
                        eventLogEntryType = EventLogEntryType.Error;
                    }
                }
                else
                {
                    if (depth == 0)
                    {
                        logContent += item.ToString();
                    }
                    else
                    {
                        logContent += ObjectDumper.Dump(item, depth);
                    }
                }

                logContent += System.Environment.NewLine;

                if (isException)
                    logContent += GetFullStackTrace();

                if (logContent.Length >= 10000)
                {
                    logContent = logContent.Substring(0, 10000);
                }

                if (string.IsNullOrEmpty(category))
                    category = "MyApp";

                #endregion

                #region Logging 

                if (!string.IsNullOrEmpty(item.ToString()))
                {
                    DateTime dt = DateTime.Now;

                    try
                    {
                        // Event log
                        EventLog l = new EventLog();
                        l.Log = "Application";
                        l.Source = category;
                        l.WriteEntry(logContent, eventLogEntryType);

                        // File
                        string logFile = dt.Year.ToString() + dt.Month.ToString().PadLeft(2, '0') + dt.Day.ToString().PadLeft(2, '0') + ".log";

                        if (!File.Exists(logFile))
                        {
                            File.Create(logFile).Close();
                        }

                        using (StreamWriter writer = new StreamWriter(logFile, true))
                        {
                            writer.WriteLine(DateTime.Now.TimeOfDay.ToString() + " " + eventLogEntryType.ToString() + " " + category + " " + logContent);
                            writer.Flush();
                        }

                        Console.WriteLine(item.ToString());
                    }
                    catch
                    {
                    }
                }
                #endregion
            }
        }

And few more examples of how you would use the above...

            List dummyList = new List();
            dummyList.Add("test 1");
            dummyList.Add("test 2");
            dummyList.Add("test 3");

            var anonymousObject = new
            {
                property1 = "test 1",
                property2 = "test 2",
                property3 = "test 3"
            };

            // String
            ("Property1 value equals " + anonymousObject.property1 + ". Is it correct?").Log();

            // Numeric
            (1.459).Log();

            // This would simply call .ToString() on the list, not very useful...
            dummyList.Log();
            // ... but, you can do this, which is much better...
            dummyList.Log(1);

            // ... and also this, in case you want to mark this log entry with something special
            dummyList.Log("My special category", 1);

            // Anonymous object
            anonymousObject.Log();
            anonymousObject.Log("My special category", 1);
            // Here, I use 'Warning' (instead of the default 'Information')
            anonymousObject.Log("My special category", System.Diagnostics.EventLogEntryType.Warning, 1);

            // Exception
            try
            {
                var zero = 0;
                var a = 1 / zero;
            }
            catch (Exception e)
            {
                e.Log();
            }
Share