Saturday, January 10, 2015

Logging utility in C#

While doing Sharepoint CSOM Automation, I have written a simple utility to create test logs. Usually CodedUI results are not stored and this utility used to capture for each run. Also trying to extend the Assert function for capturing exceptions.

namespace AutomationFramework.TestScripts { class LogFile { private String sLogFile = ConfigurationManager.AppSettings["LogResultsFile"]; public void LogMessage(String sMsg = " ") { // Create a writer and open the file: StreamWriter log; if (!File.Exists(sLogFile)) { log = new StreamWriter(sLogFile); } else { log = File.AppendText(sLogFile); } // Write to the file: log.WriteLine(DateTime.Now + " : "+ sMsg); // Close the stream: log.Close(); } public void LogAssert(bool bCondition, String sMsg=null) { bool bResult = false; try { Assert.IsTrue(bCondition,sMsg); bResult = true; } catch (Exception ex) { LogMessage("Exception: " + ex.Message); Assert.Fail("Test FAILED"); } finally { if (bResult) { LogMessage("PASS "); } } } }