private static void SendMail(string Message, LogErrorLevel MessageLogLevel) { if (MessageLogLevel <= ProtokollerConfiguration.ActualConfigInstance.ErrorLevel) //if (MessageLogLevel <= Logging.LogLevel.Warning) { lock (_stringMessageList) { _stringMessageList.Add(Message); _DateTimesList.Add(DateTime.Now); } if (myThread == null) { try { myThread = new Thread(new ThreadStart(ThreadProc)); myThread.Name = "Thread from Service: " + StaticServiceConfig.MyServiceName; myThread.Start(); _firstEntry = true; } catch (Exception ex) { LogText("Error!!!!!!", ex, Logging.LogLevel.Information); } } } }
public void Log(string message, LogErrorLevel level = LogErrorLevel.Info, Exception ex = null) { if (OnWriteLog != null && level >= LogLevel) { Task.Run(() => { OnWriteLog(message, level, ex); }); } }
//................................. private XmlNode AddMailBoxError(XmlNode inEntry, LogErrorLevelFile inErrorLevelFile, string inErrorStr, string inErrorStrDetail, bool inSent) { string timeStr = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); XmlNode error = XMLDocManager.AddNode(_errorMailBox, inEntry, @"Error"); XMLDocManager.AddAttribute(_errorMailBox, error, @"id", Convert.ToString((int)inErrorLevelFile)); XMLDocManager.AddAttribute(_errorMailBox, error, @"file", GetLogErrorLevelFileStr(inErrorLevelFile)); XMLDocManager.AddAttribute(_errorMailBox, error, @"time", timeStr); XMLDocManager.AddAttribute(_errorMailBox, error, @"sent", inSent ? @"true" : @"false"); XMLDocManager.AddAttribute(_errorMailBox, error, @"name", inErrorStr); XMLDocManager.AddAttribute(_errorMailBox, error, @"detail", inErrorStrDetail); //::::::::::::::::::::::::::::::: if (onErrorFunc != null) { LogErrorLevel errorLevel = (LogErrorLevel)Convert.ToInt32(inEntry.Attributes[@"id"].Value); onErrorFunc(errorLevel, timeStr, inErrorLevelFile, inErrorStr, inErrorStrDetail, inSent); } //::::::::::::::::::::::::::::::: return(error); }
/// <summary> Logs a message using composite string formatting. </summary> /// <param name="level"> Error level of the message. </param> /// <param name="format"> Format string. </param> /// <param name="args"> Any number of parameters used in formatting. </param> public static void Log(LogErrorLevel level, string format, params object[] args) { // escape '%'s to prevent formatting string formattedMsg = String.Format(format, args).Replace("%", "%%"); libobs.blogva((int)level, formattedMsg); }
//................................. public void ArchiveErrorMailBoxEntry(XmlDocument inErrorMailBox, LogErrorLevel inErrorLevel) { OpenErrorMailBox(inErrorMailBox); //:::::::::::::::::::::::::::::::: CopyErrorMailBoxEntry(inErrorMailBox, inErrorLevel); //:::::::::::::::::::::::::::::::::::::: XmlNode entry = GetEntry(inErrorLevel); XmlNodeList errorList = XMLDocManager.GetNodeList(entry, @"Error"); foreach (XmlNode error in errorList) { entry.RemoveChild(error); XMLDocManager.SetAttribute(entry, @"locked", @"false"); } try { SaveErrorEmailBox(inErrorMailBox, _errorMailBoxPath); } catch (Exception e) { LogWarning(string.Format(@"ArchiveErrorMailBoxEntry: Summa failed to saved error mailbox Message: {0} StackTrace: {1}", e.Message, e.StackTrace)); } //:::::::::::::::::::::::::::::::: CloseErrorMailBox(inErrorMailBox); }
private static string internalLogText(string Message, LogLevel MessageLogLevel) { if (MessageLogLevel <= SelectedLogLevel) { if (SelectedLoggingTarget == LoggingTarget.EventLog) { EventLogEntryType entrType = EventLogEntryType.Error; if (MessageLogLevel == Logging.LogLevel.Warning) { entrType = EventLogEntryType.Warning; } else if (MessageLogLevel == Logging.LogLevel.Information) { entrType = EventLogEntryType.Information; } try { eventlog.WriteEntry(Message, entrType); } catch (Exception ex) { } try { if (ProtokollerConfiguration.ActualConfigInstance.UseMailInform) { LogErrorLevel tmpLogLevel = LogErrorLevel.Error; switch (MessageLogLevel) { case LogLevel.None: tmpLogLevel = LogErrorLevel.None; break; case LogLevel.Error: tmpLogLevel = LogErrorLevel.Error; break; case LogLevel.Warning: tmpLogLevel = LogErrorLevel.Warning; break; case LogLevel.Information: tmpLogLevel = LogErrorLevel.Information; break; } SendMail(Message, tmpLogLevel); } } catch (Exception) {} } else { return(Message); } } return(null); }
/// <summary> /// format log information /// </summary> /// <param name="level">log level</param> /// <param name="message">original information</param> /// <returns>log information</returns> public StringBuilder SetLogMessage(LogErrorLevel level, string message) { var strInput = new StringBuilder(); if (level >= reportLowestErrorLevel) { try { string remoteHost = HttpContext.Current.Request.UserHostAddress; string remoteIdent = User.Identity.Name; string requestMethod = HttpContext.Current.Request.HttpMethod; string requestUrl = HttpContext.Current.Request.Url.PathAndQuery; string serverProtocol = HttpContext.Current.Request.ServerVariables["SERVER_PROTOCOL"]; int statusCode = HttpContext.Current.Response.StatusCode; string dateString = DateTime.Now.ToString(); string user = ""; if (HttpContext.Current.Session["AdministratorID"] != null) user = "******" + HttpContext.Current.Session["AdministratorID"]; else if (HttpContext.Current.Session["ExecutiveID"] != null) user = "******" + HttpContext.Current.Session["ExecutiveID"]; else if (HttpContext.Current.Session["GeneralMarketingMgrID"] != null) user = "******" + HttpContext.Current.Session["GeneralMarketingMgrID"]; else if (HttpContext.Current.Session["GeneralSalesOrgMgrID"] != null) user = "******" + HttpContext.Current.Session["GeneralSalesOrgMgrID"]; else if (HttpContext.Current.Session["MarketingID"] != null) user = "******" + HttpContext.Current.Session["MarketingID"]; else if (HttpContext.Current.Session["SalesID"] != null) user = "******" + HttpContext.Current.Session["SalesID"]; else if (HttpContext.Current.Session["RSMID"] != null) user = "******" + HttpContext.Current.Session["RSMID"]; if (string.IsNullOrEmpty(remoteIdent)) remoteIdent = "-"; if (string.IsNullOrEmpty(user)) user = "******"; strInput.Append(remoteHost + " "); strInput.Append(remoteIdent + " "); strInput.Append("[" + dateString + "] "); strInput.Append("\"" + requestMethod + " " + requestUrl + " " + serverProtocol + "\" "); strInput.Append(statusCode + " "); strInput.Append("[" + user + "] "); strInput.Append("[" + level.ToString() + "] "); strInput.Append(message + "\r\n"); } catch { strInput.Append("unknown "); strInput.Append(message + "\r\n"); } } return strInput; }
//................................. public void CopyErrorMailBoxEntry(XmlDocument inErrorMailBox, LogErrorLevel inErrorLevel) { //:::::::::::::::::::::::::::::: XmlDocument errorMailBoxEntryArchive = new XmlDocument(); // Create the XML Declaration, and append it to XML document XMLDocManager.CreateXmlDeclaration(errorMailBoxEntryArchive, @"1.0", null, null); //:::::::::::::::::::::::::::::: string entryName = LogErrorLevelToName(inErrorLevel); string timeStr = DateTime.Now.ToString("yyyyMMddHHmmss"); // Create the root element XMLDocManager.CreateRoot(errorMailBoxEntryArchive, string.Format(@"{0}{1}", timeStr, entryName)); //:::::::::::::::::::::::::::::: XmlNode archiveEntry = AddEntry(errorMailBoxEntryArchive, errorMailBoxEntryArchive.DocumentElement, entryName, inErrorLevel); //.............................. XmlNode entry = GetEntry(inErrorLevel); XmlNodeList errorList = XMLDocManager.GetNodeList(entry, @"Error"); foreach (XmlNode error in errorList) { ArchiveMailBoxError(errorMailBoxEntryArchive, archiveEntry, error.Attributes[@"id"].Value, error.Attributes[@"file"].Value, error.Attributes[@"time"].Value, error.Attributes[@"name"].Value, error.Attributes[@"detail"].Value, error.Attributes[@"sent"].Value); } //:::::::::::::::::::::::::::::::::::::: try { SaveErrorEmailBox(errorMailBoxEntryArchive, string.Format(@"{0}{1}.xml", _archiveMailBoxFolder, errorMailBoxEntryArchive.DocumentElement.Name)); LogWarning(string.Format(@"An error mailbox entry has been archived: {0}", errorMailBoxEntryArchive.DocumentElement.Name)); } catch (Exception e) { LogWarning(string.Format(@"CopyErrorMailBoxEntry: Summa failed to saved error mailbox Message: {0} StackTrace: {1}", e.Message, e.StackTrace)); } }
private string GetEntryPrefix(LogErrorLevel level) { switch (level) { case LogErrorLevel.Warning: case LogErrorLevel.Error: return(level.ToString().ToUpperInvariant() + ": "); case LogErrorLevel.Information: case LogErrorLevel.Highlight: default: return(String.Empty); } }
//................................. private XmlNode GetEntry(LogErrorLevel inErrorLevel) { XmlNodeList entries = XMLDocManager.GetNodeList(_errorMailBox, @"Entries/Entry"); foreach (XmlNode entry in entries) { if (Convert.ToInt32(entry.Attributes[@"id"].Value) == (int)inErrorLevel) { return(entry); } } return(null); }
//................................. public void LogError(LogErrorLevel inErrorLevel, LogErrorLevelFile inErrorLevelFile, string inErrorStr, string inErrorStrDetail) { try { string str = GetLogErrorStr(inErrorLevel, inErrorLevelFile, inErrorStr); //getLoggerScrErr().Log(LogLevel.Error, str); //getLoggerFileErr().Log(LogLevel.Error, str); AddMailBoxEntryError(inErrorLevel, inErrorLevelFile, inErrorStr, inErrorStrDetail); } catch (Exception) { } }
/// <summary> /// LogError /// </summary> /// <param name="strType"></param> /// <param name="strMsg"></param> public static void LogError(LogErrorLevel eLevel, string strMsg) { string strType = ""; switch (eLevel) { case LogErrorLevel.A: strType = "ERROR"; break; //case LogErrorLevel.MISC: // strType = "MISC"; // break; } m_ErrorMsgCallback(strType, strMsg); }
public string GetFormattedLogText(string text, bool addTime, LogErrorLevel level) { string outputText = String.Empty; if (!String.IsNullOrEmpty(text)) { outputText = String.Format("{0}{1}", GetEntryPrefix(level), text); if (addTime) { outputText = String.Format("{0} - {1}", DateTime.Now.ToShortTimeString(), outputText); } } return(outputText); }
public SimpleTextLogger(string logFolder, LogErrorLevel logErrorLevel = LogErrorLevel.Info) { _fileLocker = new ReaderWriterLockSlim(); LogLevel = logErrorLevel; if (!logFolder.EndsWith("\\")) { logFolder += "\\"; } if (!Directory.Exists(logFolder)) { Directory.CreateDirectory(logFolder); } LogFolder = logFolder; OnWriteLog = (message, level, exception) => { var logMsg = $"{DateTime.Now:G}\t{level}\r\n---------------\r\n{message}\r\n"; if (exception != null) { logMsg += "Error:\r\n"; logMsg += "------------------\r\n" + exception.Message + "\r\n"; logMsg += exception.StackTrace + "\r\n"; Exception innerExeption = exception.InnerException; while (innerExeption != null) { logMsg += innerExeption.Message + "\r\n"; logMsg += innerExeption.StackTrace + "\r\n"; innerExeption = innerExeption.InnerException; } logMsg += "------------------\r\n"; } logMsg += "\r\n"; _fileLocker.EnterWriteLock(); File.AppendAllText(CurrentLogFileName, logMsg); _fileLocker.ExitWriteLock(); }; }
private ConsoleColor GetForegroundColor(LogErrorLevel level) { switch (level) { case LogErrorLevel.Highlight: return(ConsoleColor.White); case LogErrorLevel.Warning: return(ConsoleColor.Yellow); case LogErrorLevel.Error: return(ConsoleColor.Red); case LogErrorLevel.Information: default: return(mOriginalConsoleColor); } }
//................................. private void AddMailBoxEntryError(LogErrorLevel inErrorLevel, LogErrorLevelFile inErrorLevelFile, string inErrorStr, string inErrorStrDetail) { OpenErrorMailBox(_errorMailBox); //:::::::::::::::::::::::::::::::: try { XmlNode entry = GetEntry(inErrorLevel); bool sent; if (!MailBoxEntryLocked(entry)) { sent = true; XmlNode error = AddMailBoxError(entry, inErrorLevelFile, inErrorStr, inErrorStrDetail, sent); SendErrorEmail(error); LockEntry(entry); } else { sent = false; AddMailBoxError(entry, inErrorLevelFile, inErrorStr, inErrorStrDetail, sent); } try { SaveErrorEmailBox(_errorMailBox, _errorMailBoxPath); } catch (Exception e) { LogWarning(string.Format(@"AddMailBoxEntryError: Summa failed to saved error mailbox Message: {0} StackTrace: {1}", e.Message, e.StackTrace)); } } catch (Exception e) { LogWarning(e.Message); } //:::::::::::::::::::::::::::::::: CloseErrorMailBox(_errorMailBox); }
public void AddLogEntry(string text, LogErrorLevel level) { bool addDateTime = !text.StartsWith(Environment.NewLine) && (!String.IsNullOrEmpty(text)); string logEntry = GetFormattedLogText(text, addDateTime, level); if (this.EchoToConsole) { Console.ForegroundColor = GetForegroundColor(level); Console.WriteLine(logEntry); //screen - only add the time Console.ForegroundColor = this.mOriginalConsoleColor; } if (addDateTime) { // add the date to the file / email log entry logEntry = String.Format("{0} {1}", DateTime.Now.ToShortDateString(), logEntry); } WriteToLogFile(logEntry); // file mLatestLog.AppendLine(logEntry); // email }
//::::::::::::::::::::::::::::::::: public string GetLogErrorLevelStr(LogErrorLevel inErrorLevel) { switch (inErrorLevel) { case LogErrorLevel.None: return(@""); case LogErrorLevel.AppFailedToStart: return(@"Summa startup"); case LogErrorLevel.SiteIDMapFailed: return(@"Site ID mapping"); case LogErrorLevel.InvalidSiteID: return(@"Site ID checking"); case LogErrorLevel.InternalXMLError: return(@"Menumate XML files processing"); case LogErrorLevel.UploadFailed: return(@"Upload files"); case LogErrorLevel.CreateZIPFailed: return(@"Creating ZIP files"); case LogErrorLevel.ServerStartListeningFailed: return(@"Summa start listening IP port"); default: return(@""); } }
//::::::::::::::::::::::::::::::::: private string LogErrorLevelToName(LogErrorLevel inErrorLevel) { switch (inErrorLevel) { case LogErrorLevel.None: return(@""); case LogErrorLevel.AppFailedToStart: return(@"SummaStartup"); case LogErrorLevel.SiteIDMapFailed: return(@"SiteIDMapping"); case LogErrorLevel.InvalidSiteID: return(@"SiteIDChecking"); case LogErrorLevel.InternalXMLError: return(@"MMXmlFilesProcessing"); case LogErrorLevel.UploadFailed: return(@"UploadFiles"); case LogErrorLevel.CreateZIPFailed: return(@"CreateZIPFiles"); case LogErrorLevel.ServerStartListeningFailed: return(@"SummaStartListeningIPPort"); default: return(@""); } }
/// <summary> /// Write to a log file. /// </summary> /// <param name="errorLevel">This is the error level of the log being written</param> /// <param name="message">This is the message to output.</param> public static void WriteToLog(LogErrorLevel errorLevel, string message) { StreamWriter errorFile = new StreamWriter(fileName); errorFile.Write(DateTime.Now.ToString() + "\t"); switch (errorLevel) { case LogErrorLevel.ERROR_NONE: errorFile.Write("ERROR_NONE\t"); break; case LogErrorLevel.ERROR_MINOR: errorFile.Write("ERROR_MINOR\t"); break; case LogErrorLevel.ERROR_MAJOR: errorFile.Write("ERROR_MOJOR\t"); break; case LogErrorLevel.ERROR_CRITICAL: errorFile.Write("ERROR_CRITICAL\t"); break; case LogErrorLevel.ERROR_WARNING: errorFile.Write("ERROR_WARNING\t"); break; case LogErrorLevel.ERROR_INFO: errorFile.Write("ERROR_INFO\t"); break; } errorFile.WriteLine(message); Console.WriteLine(message); }
//................................. private XmlNode AddEntry(XmlDocument inErrorMailBox, XmlNode inEntries, string inEntryName, LogErrorLevel inErrorLevel) { XmlNode entry = XMLDocManager.AddNode(inErrorMailBox, inEntries, @"Entry"); XMLDocManager.AddAttribute(inErrorMailBox, entry, @"name", inEntryName); XMLDocManager.AddAttribute(inErrorMailBox, entry, @"id", Convert.ToString((int)inErrorLevel)); XMLDocManager.AddAttribute(inErrorMailBox, entry, @"locked", @"false"); return(entry); }
/// <summary> /// write log to file. /// </summary> /// <param name="level">log level</param> /// <param name="message">log information</param> public void WriteLog(LogErrorLevel level, string message) { lock (Finfo) { StreamWriter writer = null; try { writer = Finfo.AppendText(); StringBuilder strInput = SetLogMessage(level, message); writer.Write(strInput); } catch (Exception x) { StringBuilder strInput = SetLogMessage(level, message); var conn = new SqlConnection(SQLHelper.ConnectionString); conn.Open(); string sqlstr = "Insert into Log(Message,LogFileError) Values(@Message,@LogFileError)"; var cmd = new SqlCommand(sqlstr, conn); cmd.Parameters.AddWithValue("@Message", strInput.ToString()); cmd.Parameters.AddWithValue("@LogFileError", x.ToString()); cmd.ExecuteNonQuery(); conn.Close(); } finally { if (writer != null) { writer.Flush(); writer.Close(); } } } }
//::::::::::::::::::::::::::::::::: private string GetLogErrorStr(LogErrorLevel inErrorLevel, LogErrorLevelFile inErrorLevelFile, string inErrorStr) { return(string.Format("Error: {0} : {1} : {2}", GetLogErrorLevelStr(inErrorLevel), GetLogErrorLevelFileStr(inErrorLevelFile), inErrorStr)); }
/// <summary> Logs a message. </summary> /// <param name="level"> Error level of the message. </param> /// <param name="message"> Message. </param> public static void Log(LogErrorLevel level, string message) { // escape '%'s to prevent formatting libobs.blogva((int)level, message.Replace("%", "%%")); }
/// <summary> Logs a message using C-style printf formatting. </summary> /// <param name="level"> Error level of the message. </param> /// <param name="format"> Format string. </param> /// <param name="args"> Any number of parameters used in formatting. </param> public static void Logf(LogErrorLevel level, string format, params object[] args) { // let libobs handle the formatting libobs.blogva((int)level, format, args); }