using System.IO;
using Microsoft.SharePoint.Administration;
//Below are the methods can be used to log exception in files or in ULS logs
private void WriteLog(string LogText)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
string fullFileName = GetValueByKey(CONFIG_LOG_FILEPATH);
string folderpath = string.Empty;
string fileName = string.Empty;
string ext = string.Empty;
string file = fullFileName;
folderpath = file.Remove(file.LastIndexOf("\\") + 1);
fileName = file.Substring(file.LastIndexOf("\\") + 1);
ext = fileName.Substring(fileName.LastIndexOf("."));
fileName = fileName.Remove(fileName.LastIndexOf("."));
string LogFilePath = folderpath + fileName + ext; ;
if (File.Exists(fullFileName))
{
FileInfo fi = new FileInfo(fullFileName);
long size = fi.Length;
if (size > 10485760)
{
string date = DateTime.Today.Year.ToString() + DateTime.Today.Month.ToString() + DateTime.Today.Day.ToString();
string time = DateTime.Now.TimeOfDay.Hours.ToString() + DateTime.Now.TimeOfDay.Minutes.ToString() + DateTime.Now.TimeOfDay.Seconds.ToString();
string dateTime = date + "T" + time;
string newPath = folderpath + fileName + "_" + dateTime + ext;
File.Copy(LogFilePath, newPath);
File.Delete(LogFilePath);
}
}
StreamWriter SW;
SW = File.AppendText(LogFilePath);
SW.WriteLine(DateTime.Now + ":~Workflow Round 2~:" + LogText);
SW.Close();
});
}
catch (Exception ex)
{
LogMessage(ex);
}
}
/// <summary>
/// Private method Logs Error Message
/// </summary>
/// <param name="severity">TraceSeverity severity</param>
/// <param name="message">String Message</param>
private void LogMessage(TraceSeverity severity, string message)
{
try
{
uint uintEventID = 8000;//event ID
string CategoryName = "Log Message";
SPDiagnosticsCategory category = new SPDiagnosticsCategory(CategoryName, TraceSeverity.Medium, EventSeverity.Error);
SPDiagnosticsService.Local.WriteTrace(uintEventID, category, TraceSeverity.Unexpected, message);
}
catch (Exception ex)
{
WriteLog(ex.Message.ToString());
LogMessage(ex);
}
}
/// <summary>
/// Log Error Message
/// </summary>
/// <param name="ex">Exception ex</param>
public void LogMessage(Exception ex)
{
LogMessage(TraceSeverity.High, ex.Message + ex.StackTrace);
}
/// <summary>
/// Log Message
/// </summary>
/// <param name="message">string</param>
public void LogMessage(string message)
{
LogMessage(TraceSeverity.Medium, message);
}
No comments:
Post a Comment