Thursday, May 19, 2016

Old codes worth sharing : Simple c# class that logs to a file

A simple c# class that logs to a file.
Some of the exception formatting adopted from one of @robconery tutorial session way back years ago :)


using System;
using System.IO;

namespace Code2016
{
    [Serializable]
    internal class WriteLog
    {
        // Methods
        public static string Write(string methodName, Exception exception)
        {
            string logs = LogFormater(exception, methodName);
            WriteToLogFile(logs);
            return logs;
        }

        public static string Write(string methodName, string exception)
        {
            string logs = LogFormater(exception, methodName);
            WriteToLogFile(logs);
            return logs;
        }

        private static void WriteToLogFile(string logs)
        {
            //StreamWriter writer = new StreamWriter(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\" + DateTime.Now.ToString("ddMMyyyy") + ".log", true);
            StreamWriter writer = new StreamWriter(@"C:\BizTalk_Dropzone\Merak942\Logs\" + DateTime.Now.ToString("yyyyMMdd") + ".log", true);
            writer.WriteLine(logs);
            writer.Close();
        }

        private static string LogFormater(Exception exception, string methodName)
        {
            string content = string.Format("Date/Time: {0}{1}", DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss"), Environment.NewLine);
            content += string.Format("Method Name: {0}{1}", methodName, Environment.NewLine);
            content += string.Format("Error Details: {0}{1}", exception.Message, Environment.NewLine);
            content += string.Format("Source: {0}{1}", exception.Source, Environment.NewLine);
            content += string.Format("Stack Trace: {0}{1}{1}{1}", exception.StackTrace, Environment.NewLine);
            return content;
        }

        private static string LogFormater(string exception, string methodName)
        {
            string content = string.Format("Date/Time: {0}{1}", DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss"), Environment.NewLine);
            content += string.Format("Method Name: {0}{1}", methodName, Environment.NewLine);
            content += string.Format("Error Details: {0}{1}", exception, Environment.NewLine);
            return content;
        }
    }
}

No comments:

Post a Comment