Log error in a separate file

You can log your applications errors in separate text file. Use this code

public static void WriteException(string msg)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string LogFile = SPUtility.GetVersionedGenericSetupPath("LOGS",15) + "\\SPErrorLog-" + DateTime.Today.ToString("MM-dd-yyyy") + ".txt";
                    StringBuilder sMessage = new StringBuilder();
                    msg = msg.Replace("<b>", "");
                    msg = msg.Replace("</b>", "");
                    msg = msg.Replace("<HR/>", "");

                    sMessage.AppendLine("--------------------------------------------------------------------------------------------------------------------------------------------");
                    sMessage.AppendLine(msg);

                    if (!File.Exists(LogFile))
                    {
                        StreamWriter sw = File.CreateText(LogFile);
                        sw.WriteLine(sMessage);
                        sw.Close();
                    }
                    else
                    {
                        StreamWriter sw = File.AppendText(LogFile);
                        sw.WriteLine(sMessage);
                        sw.Close();
                    }
                });
            }
            catch { }
        }

Comments

Popular Posts

SharePoint Interview Questions and Answers

Download Infopath Form Templates

How to get current logged user information using JavaScript ?

Steps to set Form based authentication (FBA) for SharePoint 2010

SharePoint Interview Questions and Answers II

Get List Items - JavaScript

Change Language for current user with JSOM in SharePoint Online

Cross Site List Rollup Web Part for SharePoint 2010

Hide Recently Modified Items

SharePoint 2010 CSS Chart