Friday, February 10, 2012

Generic Logger for WCF Request/Response

Generic Logger
Below class represent an example for generics class which would log all request and response object data in xml format.

public sealed class LogManager<T>
    {
        private LogManager()
       {

       }
      
        private static string IsLogRequestEnable = ConfigurationManager.AppSettings["IsLogRequestEnable"];
        private static string IsLogResponseEnable = ConfigurationManager.AppSettings["IsLogResponseEnable"];
        private static string IsLogErrorEnable = ConfigurationManager.AppSettings["IsLogErrorEnable"];
        private static string LogDirPath = ConfigurationManager.AppSettings["LogDirPath"];
        private static string LogFileName = ConfigurationManager.AppSettings["LogFileName"];
        private static string ErrorLogFileName = ConfigurationManager.AppSettings["ErrorLogFileName"];
        private static string CurruntDateFolderPath = null;
        private static string CurruntDateTimeStamp = null;
        private static string XmlLogFileName = null;
        private static string XmlErrorLogFileName = null;
        private static object sync = new object();

         private static void CreateLogDirectory()
         {
              string CurruntDate = DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Year;             
              CurruntDateFolderPath = LogDirPath + "\\" + CurruntDate;

              if (!(Directory.Exists(LogDirPath)))
              {
                  Directory.CreateDirectory(LogDirPath);

                  if (!(Directory.Exists(CurruntDateFolderPath)))
                  {
                      Directory.CreateDirectory(CurruntDateFolderPath);

                    }
              }
              else
              {

                  if (!(Directory.Exists(CurruntDateFolderPath)))
                  {
                      Directory.CreateDirectory(CurruntDateFolderPath);
                    }
              }
        
         }
         private static void LogRequestBackup(T requestObject)
        {
               string CurruntDate = DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Year;
               string CurruntDateFolderPath = null;
               CurruntDateFolderPath = LogDirPath + "\\" + CurruntDate;
            lock (sync)
            {
                //if (!(Directory.Exists(LogDirPath)))
                //    Directory.CreateDirectory(LogDirPath);

                //if (!(Directory.Exists(CurruntDateFolderPath)))
                //    Directory.CreateDirectory(CurruntDateFolderPath);

                ////check the file

                //string LoggerFileName = DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Year;// +"_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + DateTime.Now.Second;

                FileStream fileStream = new FileStream(CurruntDateFolderPath + "\\" + LogFileName + "_" + CurruntDateTimeStamp + ".xml", FileMode.Append, FileAccess.Write);
                using (StreamWriter writer = new StreamWriter(fileStream))
                {
                    writer.Write("<LogRequest>");
                    writer.WriteLine(Environment.NewLine);
                    writer.Write(GetXML(requestObject));
                    writer.WriteLine(Environment.NewLine);
                    writer.Write("</LogRequest>");
                    writer.WriteLine(Environment.NewLine);
                }
            }

        }
       
        public static void LogRequest(T requestObject,string guid)
        {

            if (IsLogRequestEnable=="true")
            {
                lock (sync)
                {
                    CreateLogDirectory();
                    CurruntDateTimeStamp = DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Year + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute;// +DateTime.Now.Second;
                    XmlLogFileName = CurruntDateFolderPath + "\\" + LogFileName + CurruntDateTimeStamp + ".xml";


                    XmlDocument logRequest = new XmlDocument();

                    try
                    {
                        logRequest.Load(XmlLogFileName);
                    }

                    catch (FileNotFoundException)
                    {
                        XmlTextWriter createFile = new XmlTextWriter(XmlLogFileName, System.Text.Encoding.UTF8);
                        createFile.Formatting = Formatting.Indented;
                        createFile.WriteProcessingInstruction("xml", "version = '1.0' encoding = 'UTF-8'");
                        createFile.WriteStartElement("CheckGatewayLog");
                        createFile.Close();
                        logRequest.Load(XmlLogFileName);
                    }
                    XmlNode rootElement = logRequest.DocumentElement;
                    XmlElement child = logRequest.CreateElement("Request");
                    child.SetAttribute("LogID", guid.ToString());
                    child.InnerText = GetXML(requestObject);
                    rootElement.AppendChild(child);
                    logRequest.Save(XmlLogFileName);
                }
            }
        }

        public static void LogError(T requestObject)
        {

            if (IsLogErrorEnable == "true")
            {

                lock (sync)
                {
                    CurruntDateTimeStamp = DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Year + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute;// +DateTime.Now.Second;
                    XmlErrorLogFileName = CurruntDateFolderPath + "\\" + ErrorLogFileName + CurruntDateTimeStamp + ".xml";
                    CreateLogDirectory();
                    XmlDocument logRequest = new XmlDocument();
                    try
                    {
                        logRequest.Load(XmlErrorLogFileName);
                    }

                    catch (FileNotFoundException)
                    {
                        XmlTextWriter createFile = new XmlTextWriter(XmlErrorLogFileName, System.Text.Encoding.UTF8);
                        createFile.Formatting = Formatting.Indented;
                        createFile.WriteProcessingInstruction("xml", "version = '1.0' encoding = 'UTF-8'");
                        createFile.WriteStartElement("CheckGatewayErrorLog");
                        createFile.Close();
                        logRequest.Load(XmlErrorLogFileName);

                    }
                    XmlNode rootElement = logRequest.DocumentElement;
                    XmlElement child = logRequest.CreateElement("ErrorInfo");

                    child.InnerText = GetXML(requestObject);
                    rootElement.AppendChild(child);
                    logRequest.Save(XmlErrorLogFileName);
                }
            }
        }
        public static void LogResponse(T responseObject, string guid)
        {
            if (IsLogRequestEnable == "true")
            {

                lock (sync)
                {
                    CurruntDateTimeStamp = DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Year + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute;// +DateTime.Now.Second;
                    XmlLogFileName = CurruntDateFolderPath + "\\" + LogFileName + CurruntDateTimeStamp + ".xml";
                    XmlDocument logResponse = new XmlDocument();
                    CreateLogDirectory();
                    try
                    {
                        logResponse.Load(XmlLogFileName);
                    }

                    catch (FileNotFoundException)
                    {
                        XmlTextWriter createFile = new XmlTextWriter(XmlLogFileName, System.Text.Encoding.UTF8);
                        createFile.Formatting = Formatting.Indented;
                        createFile.WriteProcessingInstruction("xml", "version = '1.0' encoding = 'UTF-8'");
                        createFile.WriteStartElement("CheckGatewayLog");
                        createFile.Close();
                        logResponse.Load(XmlLogFileName);
                    }
                    XmlNode rootElement = logResponse.DocumentElement;
                    XmlElement child = logResponse.CreateElement("Response");
                    child.SetAttribute("LogID", guid.ToString());
                    child.InnerText = GetXML(responseObject);
                    rootElement.AppendChild(child);
                    logResponse.Save(XmlLogFileName);
                }
            }
        }

        private static string GetXML(T Obj)
        {
            MemoryStream stream = null;
            TextWriter writer = null;
            //XmlWriter writer = null;
            try
            {
                stream = new MemoryStream(); // read xml in memory
                writer = new StreamWriter(stream, Encoding.UTF8);
                //Create our own namespaces for the output
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                //Add an empty namespace and empty value
                ns.Add("", "");
                // get serialise object
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(writer, Obj,ns); // read object
                int count = (int)stream.Length; // saves object in memory stream
                byte[] arr = new byte[count];
                stream.Seek(0, SeekOrigin.Begin);
                // copy stream contents in byte array
                stream.Read(arr, 0, count);            
                System.Text.UTF8Encoding utf = new UTF8Encoding();// convert byte array to string
                var result = utf.GetString(arr).Trim();
                result = result.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
                return result;
            }
            catch (Exception ex)
            {
                return "Exception Occured in Writer" + ex.Message.ToString();
            }
            finally
            {
                if (stream != null) stream.Close();
                if (writer != null) writer.Close();
            }
        }

    }

DataContract:
[DataContract]
   public class CheckMeRequest
    {
        [DataMember]
       
        [StringLengthValidator(0, 50,MessageTemplate="Input Param can not be null. Please try again!")]
        public string Echo
        {
            get;
            set;
        }
    }


 [DataContract]
    public class CheckMeResponse
    {
         [DataMember]
         public string Response
         {
             get;
             set;
         }
    }




Calling code:
  public CheckMeResponse CheckMe(CheckMeRequest echoString)
        {
            LogManager<CheckMeRequest>.LogRequest(echoString, GUID);
            var result=RequestValidator<CheckMeRequest>.ValidateRequest(echoString);
            CheckMeResponse checkMeResponse = new CheckMeResponse();
            if(!string.IsNullOrEmpty(result))
            {
                checkMeResponse.Response = result;
            }
            else
            {          
                checkMeResponse.Response = echoString.Echo;
            }
            LogManager<CheckMeResponse>.LogResponse(checkMeResponse, GUID);
            return checkMeResponse;
        }

Logfile:

No comments:

Post a Comment