//TODO: Logger - make sure this does not cause any slowness due to long logger construction time public static void Log(string logger, logLevel loglevel, string message) { ILog loggerObj = LogManager.GetLogger(logger); switch (loglevel) { case logLevel.DEBUG: loggerObj.Debug(message); break; case logLevel.INFO: loggerObj.Info(message); break; case logLevel.WARN: loggerObj.Warn(message); break; case logLevel.ERROR: loggerObj.Error(message); break; case logLevel.FATAL: loggerObj.Fatal(message); break; } }
/// <summary> /// 输出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="msg"></param> #region static void WriteLog(Type t, string msg,logLevel ll= logLevel.DEBUG) public static void WriteLog(Type t, string msg, logLevel ll = logLevel.DEBUG) { log4net.ILog log = log4net.LogManager.GetLogger(t); switch (ll) { case logLevel.DEBUG: log.Debug(msg); break; case logLevel.INFO: log.Info(msg); break; case logLevel.WARN: log.Warn(msg); break; case logLevel.ERROR: log.Error(msg); break; case logLevel.FATAL: log.Fatal(msg); break; default: break; } }
static void PrintLog(logLevel lev, params string[] args) { if (_logPath.Length == 0) { return; } if (lev < logFilter) { return; } string label = "D"; switch (lev) { case logLevel.trace: label = "T"; break; case logLevel.warning: label = "W"; break; case logLevel.error: label = "E"; break; } try { System.IO.StreamWriter w = System.IO.File.AppendText(_logPath); w.WriteLine("{0:yyyy-MM-dd HH:mm:ss} {1} {2}", DateTime.UtcNow, label, String.Join(" ", args)); w.Close(); } catch (Exception ex) { Console.WriteLine("Cannot write to {0} {1}", _logPath, ex); } }
/// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="level"></param> public void log(string message, logLevel level) { if (this.instance != null) { switch (level) { case logLevel.Error: this.instance.Error(message); break; case logLevel.Fatal: this.instance.Fatal(message); break; case logLevel.Information: this.instance.Info(message); break; case logLevel.Warning: this.instance.Warn(message); break; case logLevel.Debug: this.instance.Debug(message); break; } } }
/// <summary> /// 输出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="ex"></param> #region static void WriteLog(Type t, Exception ex,logLevel ll= logLevel.DEBUG) public static void WriteLog(Type t, Exception ex, logLevel ll = logLevel.DEBUG) { log4net.ILog log = log4net.LogManager.GetLogger(t); switch (ll) { case logLevel.DEBUG: log.Debug("Error", ex); break; case logLevel.INFO: log.Info("Error", ex); break; case logLevel.WARN: log.Warn("Error", ex); break; case logLevel.ERROR: log.Error("Error", ex); break; case logLevel.FATAL: log.Fatal("Error", ex); break; default: break; } }
/// <summary> /// Log a string with the given log level /// </summary> /// <param name="level"></param> /// <param name="toLog"></param> protected void log(logLevel level, string toLog) { Debug.WriteLine(toLog); if (onLogString == null) return; onLogString.Invoke(Enum.GetName(typeof(logLevel), level).ToString() + ": " + toLog); }
public Logger(ref AutomationsEntities p_objMyDB, string p_strSessionID, logLevel p_objLogLevel = logLevel.ErrorOnly, string p_strClassName = "") { m_objLogLevel = p_objLogLevel; m_objMemoryLog = new StringBuilder(); myDB = p_objMyDB; m_strSessionID = p_strSessionID; m_strClassName = p_strClassName; }
/// <summary>Schreibt einen neuen Providerspezifischen Logeintrag.</summary> protected void writeLogEntry(logLevel level, string message) { Session.Log.writeKeyValue(level, string.Format("[{0}] [{1}]", Session.publishFactory.availableProvider[GetType()].Name, Settings.Name), message ); }
/// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="level"></param> public void appendMessage(publisher publisher, string message, logLevel level) { if (!this.textBoxContent.InvokeRequired) { this.textBoxContent.AppendText(string.Format("{0}: {1}\r\n", DateTime.Now.ToString("MMM dd HH.mm.ss"), message)); } else { this.textBoxContent.Invoke(new dlgPublisherStatus(this.appendMessage), new object[] { publisher, message, level }); } }
public SCLog( string extensionName = DEFAULT_EXT, string extensionSignature = DEFAULT_SIG, DateTime startTime = new DateTime(), logLevel stdOutLevel = logLevel.None, string functionServed = "Not Specified", string callingFile = "Not Specified" ) { this.extName = extensionName; this.extSignature = extensionSignature; this.startTime = startTime; this.stdOutputThreshold = stdOutLevel; this.functionServed = functionServed; this.callingFile = callingFile; }
private static void logAuto(string text, logLevel level) { if (level == logLevel.Disabled) { level = logLevel.Info; } if (text != null) { if (level == logLevel.Warning && LogLevel == logLevel.Warning) { Debug.LogWarning(text); } else if (level == logLevel.Info && LogLevel >= logLevel.Info) { Debug.Log(text); } } }
private void writeLogInternal(logLevel level, string message) { //Do nothing if logging is turned off if (!_session.Settings.enableLogging) { return; } //Create Logdirectory if (!Directory.Exists(_logDirectory)) { Directory.CreateDirectory(_logDirectory); } using (var writer = new StreamWriter(Path.Combine(_logDirectory, _logSessionFilename), true, Encoding.UTF8)) { writer.WriteLine(string.Format("[{0}] [{1}] {2}{3}", new object[] { DateTime.Now.ToString(), level, logDepthSpace, message })); writer.Flush(); } }
public ProjectorLift(string p_strName, string p_strCOM, int p_strMoveTime, string p_strCurrentSession, logLevel p_objLogLevel = logLevel.ErrorOnly) { LiftName = p_strName; LiftCOMPort = p_strCOM; LiftMoveTime = p_strMoveTime; myDB = new AutomationsEntities(); m_objLogger = new Logger(ref myDB, p_strCurrentSession, p_objLogLevel, "ProjectorLift()"); }
private void writeLogInternal(logLevel level, string message) { //Do nothing if logging is turned off if (!_session.Settings.enableLogging) return; //Create Logdirectory if (!Directory.Exists(_logDirectory)) Directory.CreateDirectory(_logDirectory); using(var writer = new StreamWriter(Path.Combine(_logDirectory, _logSessionFilename), true, Encoding.UTF8)) { writer.WriteLine(string.Format("[{0}] [{1}] {2}{3}", new object[] { DateTime.Now.ToString(), level, logDepthSpace, message })); writer.Flush(); } }
public Projector(string p_strName, string p_strIP, string p_strLiftAssociation, string p_strCurrentSession, logLevel p_objLogLevel = logLevel.ErrorOnly) { projectorName = p_strName; projectorIP = p_strIP; projectorLiftAssociation = p_strLiftAssociation; m_objProjectorConnection = null; myDB = new AutomationsEntities(); m_objLogger = new Logger(ref myDB, p_strCurrentSession, p_objLogLevel, "Projector()"); }
/// <summary> /// Log an event at the given log level /// </summary> /// <param name="level"></param> /// <param name="toLog"></param> protected void log(logLevel level, string toLog) { if (onLog != null) onLog.Invoke(level, toLog); }
static void Main(string[] args) { bool run = true; // parse command line arguments int expectedArgc = 2; for (int i = 0; i < args.Length; i++) { // print help if (args[i] == "-h") { print_usage(); return; } // enable log file if (args[i] == "-l") { if (i >= args.Length - 1) { print_usage(); return; } _logPath = args[i + 1]; expectedArgc += 2; } // set loglevel filter if (args[i] == "-f") { if (i >= args.Length - 1) { print_usage(); return; } switch (args[i + 1][0]) { case 'E': logFilter = logLevel.error; break; case 'W': logFilter = logLevel.warning; break; case 'T': logFilter = logLevel.trace; break; case 'D': logFilter = logLevel.debug; break; default: print_usage(); return; } expectedArgc += 2; } // performance mode if (args[i] == "-p") { performance = true; expectedArgc += 1; } } // min expected arguments is 2 (IP and port) if (args.Length < expectedArgc) { print_usage(); return; } string addr; ushort port; try { addr = args[expectedArgc - 2]; port = Convert.ToUInt16(args[expectedArgc - 1]); } catch { print_usage(); return; } PrintLog(logLevel.trace, "Connecting to ", addr, ":", Convert.ToString(port)); Console.WriteLine("Connecting to {0}:{1}", addr, port); try { // connect to the ciupServer NativeMethods.ciupDataCbDelegate pDataCb = ciupDataCb; NativeMethods.ciupErrorCbDelegate pErrorCb = ciupErrorCb; int id = NativeMethods.ciupcConnect(addr, port, pDataCb, pErrorCb); if (id < 0) { PrintLog(logLevel.error, "Cannot connect"); Console.WriteLine("Cannot connect"); return; } PrintLog(logLevel.trace, "Connection id: ", id.ToString()); Console.WriteLine("Connection id: {0}", id); // intercept [CTRL][c] while sleeping Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) { PrintLog(logLevel.trace, "[CTRL][c]"); Console.WriteLine("[CTRL][c]"); e.Cancel = true; run = false; }; while (run) { System.Threading.Thread.Sleep(5000); // discomment to receive some serverinfo packets NativeMethods.ciupcInfo(id); } // close connection NativeMethods.ciupcStop(id); NativeMethods.ciupcDisconnect(id); } catch (Exception e) { PrintLog(logLevel.trace, e.ToString()); Console.WriteLine($"Error: {e}"); } }
public LogEntry(logLevel level, string message, string source) { this.Message = message; this.Level = level; this.Source = source; }
public static void LogExceptions(String className, String method, String message, String lineNumber, logLevel level) { try { //Get the path from the config string configLogFile = ConfigurationManager.AppSettings["logFileName"].ToString(); string path = "~/" + configLogFile; //Check if the file exists or not, If not create one if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) { File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close(); } //Open the file for reading using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))) { //Get the log level string configLogLevel = ConfigurationManager.AppSettings["loglevel"].ToString(); int configintlevel; bool isNumeric = int.TryParse(configLogLevel, out configintlevel); //If the log level is set only for EXCEPTIONS if (isNumeric && level == logLevel.Exception && configintlevel > 0) { w.Write("EXCEPTION :: "); w.WriteLine(" {0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)); w.WriteLine(" AT {0} :: {1} - {2}", className, method, lineNumber); w.WriteLine(" EXception Message :: " + message); } w.Flush(); w.Close(); } } catch (Exception ex) { var stackTrace = new StackTrace(ex, true); var line = stackTrace.GetFrame(0).GetFileLineNumber(); Logger.LogExceptions(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, ex.Message, line.ToString(), Logger.logLevel.Exception); } }
Custom(source, message, logLevel, MetaType.System, values);
public void writeState(logLevel level, string state) { writeLogInternal(level, state); }
public void writeKeyValue(logLevel level, string key, string value) { writeLogInternal(level, string.Format("{0}: {1}", key, value)); }
foreach (var(logLevel, @string) in logLevelStrings)
public Boolean log(string message, string detail = null, Incident incident = null, Contact contact = null, string source = null, string function = null, int timeElapsed = 0, logLevel messageType = logLevel.Debug, string host = null, int processID = 0) { if (this.extConfigs == null) { throw new Exception("SCLog has not been initialized"); } if ((int)messageType > this.extConfigs.logThreshhold) { return(false); } GenericObject go = new GenericObject { ObjectType = new RNObjectType { Namespace = "SvcVentures", // Custom Object TypeName = "scLog" // Custom Object } }; List <GenericField> fields = new List <GenericField>(); if (message.Length > 255) { message = message.Substring(0, 255); } fields.Add(createGenericField("Message", ItemsChoiceType.StringValue, message)); fields.Add(createGenericField("MsgType", ItemsChoiceType.IntegerValue, (int)messageType)); long memory = GC.GetTotalMemory(true) / (1024 * 1024); fields.Add(createGenericField("PeakMemory", ItemsChoiceType.IntegerValue, (int)memory)); if (string.IsNullOrWhiteSpace(source) == false) { fields.Add(createGenericField("File", ItemsChoiceType.StringValue, trimMaxLengthString(source))); } if (string.IsNullOrWhiteSpace(function) == false) { fields.Add(createGenericField("Function", ItemsChoiceType.StringValue, trimMaxLengthString(function))); } if (string.IsNullOrWhiteSpace(detail) == false) { fields.Add(createGenericField("Detail", ItemsChoiceType.StringValue, trimMaxLengthString(detail))); } if (string.IsNullOrWhiteSpace(host) == false) { fields.Add(createGenericField("Host", ItemsChoiceType.StringValue, trimMaxLengthString(host))); } fields.Add(createGenericField("ProcessID", ItemsChoiceType.IntegerValue, processID)); fields.Add(createGenericField("TimeElapsed", ItemsChoiceType.IntegerValue, timeElapsed)); fields.Add(createGenericField("scProductExtension", ItemsChoiceType.NamedIDValue, new NamedID { ID = new ID { id = (int)this.extObject.ID.id, idSpecified = true } } )); if (!string.IsNullOrWhiteSpace(detail)) { fields.Add(createGenericField("Detail", ItemsChoiceType.StringValue, trimMaxLengthString(detail))); } go.GenericFields = fields.ToArray(); CreateProcessingOptions cpo = new CreateProcessingOptions(); cpo.SuppressExternalEvents = false; cpo.SuppressRules = false; ClientInfoHeader clientInfoHeader = new ClientInfoHeader(); clientInfoHeader.AppID = "Insert log"; RNObject[] results = this.client.Create(clientInfoHeader, new RNObject[] { go }, cpo); // check result and save incident id if (results != null && results.Length > 0) { bool xRefsPresent = false; GenericObject xRefObj = new GenericObject { ObjectType = new RNObjectType { Namespace = "SvcVentures", // Custom Object TypeName = "scLogXref" // Custom Object } }; List <GenericField> xRefFields = new List <GenericField>(); if (incident != null) { xRefsPresent = true; xRefFields.Add(createGenericField("Incident", ItemsChoiceType.NamedIDValue, new NamedID { ID = new ID { id = (int)incident.ID.id, idSpecified = true } })); } if (contact != null) { xRefsPresent = true; xRefFields.Add(createGenericField("Contact", ItemsChoiceType.NamedIDValue, new NamedID { ID = new ID { id = (int)contact.ID.id, idSpecified = true } })); } if (xRefsPresent == false) { return(true); } xRefFields.Add(createGenericField("scLog", ItemsChoiceType.NamedIDValue, new NamedID { ID = new ID { id = (int)results[0].ID.id, idSpecified = true } } )); xRefObj.GenericFields = xRefFields.ToArray(); RNObject[] xRefResults = this.client.Create(clientInfoHeader, new RNObject[] { xRefObj }, cpo); return(true); } else { return(false); } }
public static void appendMessage(string message, logLevel level) { screenManager.instScreen.appendMessage(null, message, level); }
/// <summary>Schreibt einen neuen Providerspezifischen Logeintrag.</summary> protected void writeLogEntry(logLevel level, string message) { Session.Log.writeKeyValue(level, string.Format("[{0}] [{1}]", Session.publishFactory.availableProvider[GetType()].Name, Settings.Name), message ); }
_remoteApi = RestService.For <IRemoteApi>(HttpClientFactory.GetHttpClient(logLevel, timeout));
public void writeKeyValue(logLevel level, string key, string value) { writeLogInternal(level, string.Format("{0}: {1}", key, value)); }
/// <summary> /// /// </summary> /// <param name="publisher"></param> /// <param name="status"></param> /// <param name="level"></param> private static void instPublisher_shareStatus(publisher publisher, string status, logLevel level) { screenManager.appendMessage(status, level); }
public void writeState(logLevel level, string state) { writeLogInternal(level, state); }
public static void LogDebug(String className, String method, String message, logLevel level) { try { //Get the path from the config string configLogFile = ConfigurationManager.AppSettings["logFileName"].ToString(); string path = "~/" + configLogFile; //Check if the file exists or not, If not create one if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) { File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close(); } //Open the file for reading using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))) { //Get the log level string configLogLevel = ConfigurationManager.AppSettings["loglevel"].ToString(); int configintlevel; bool isNumeric = int.TryParse(configLogLevel, out configintlevel); //If the log level is set for DEBUG if (isNumeric && level == logLevel.Debug && configintlevel > 1) { w.Write("DEBUG :: "); w.WriteLine("\n AT {0} :: {1} ", className, method); w.WriteLine(" Input parameters - {0}", message); } else if (isNumeric && level == logLevel.Info && configintlevel > 1) { w.Write("INFO :: "); w.WriteLine("\n AT {0} :: {1} ", className, method); w.WriteLine(" {0}", message); } //If the log level is set for QUERY TIMER else if (isNumeric && (level == logLevel.TimerStart) && configintlevel > 2) { w.Write(" TIMER : Timer Start time - "); w.WriteLine(" AT {0} :: {1} ", className, method); w.WriteLine("{0}", message); } //If the log level is set for QUERY TIMER else if (isNumeric && (level == logLevel.TimerEnd) && configintlevel > 2) { w.Write(" TIMER : Timer End time - "); w.WriteLine(" AT {0} :: {1} ", className, method); w.WriteLine("{0}", message); } w.Flush(); w.Close(); } } catch (Exception ex) { var stackTrace = new StackTrace(ex, true); var line = stackTrace.GetFrame(0).GetFileLineNumber(); Logger.LogExceptions(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, ex.Message, line.ToString(), Logger.logLevel.Exception); } }
AddLogData(new LogData(logLevel, data));
public static void LogExceptions(String className, String method, String message, String lineNumber, logLevel level) { try { //Get the path from the config string configLogFile = ConfigurationManager.AppSettings["logFileName"].ToString(); string path = "~/" + configLogFile; //Check if the file exists or not, If not create one if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) { File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close(); } //Open the file for reading using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))) { //Get the log level string configLogLevel = ConfigurationManager.AppSettings["loglevel"].ToString(); int configintlevel; bool isNumeric = int.TryParse(configLogLevel, out configintlevel); //If the log level is set only for EXCEPTIONS if (isNumeric && level == logLevel.Exception && configintlevel > 0) { w.Write("EXCEPTION :: "); w.WriteLine(" {0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)); w.WriteLine(" AT {0} :: {1} - {2}", className, method, lineNumber); w.WriteLine(" EXception Message :: " + message); } w.Flush(); w.Close(); } } catch (Exception ex) { var stackTrace = new StackTrace(ex, true); var line = stackTrace.GetFrame(0).GetFileLineNumber(); Logger.LogExceptions(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, ex.Message, line.ToString(), Logger.logLevel.Exception); } }
public static void LogDebug(String className, String method, String message, logLevel level) { try { //Get the path from the config string configLogFile = ConfigurationManager.AppSettings["logFileName"].ToString(); string path = "~/" + configLogFile; //Check if the file exists or not, If not create one if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) { File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close(); } //Open the file for reading using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))) { //Get the log level string configLogLevel = ConfigurationManager.AppSettings["loglevel"].ToString(); int configintlevel; bool isNumeric = int.TryParse(configLogLevel, out configintlevel); //If the log level is set for DEBUG if (isNumeric && level == logLevel.Debug && configintlevel > 1) { w.Write("DEBUG :: "); w.WriteLine("\n AT {0} :: {1} ", className, method); w.WriteLine(" Input parameters - {0}", message); } else if (isNumeric && level == logLevel.Info && configintlevel > 1) { w.Write("INFO :: "); w.WriteLine("\n AT {0} :: {1} ", className, method); w.WriteLine(" {0}", message); } //If the log level is set for QUERY TIMER else if (isNumeric && (level == logLevel.TimerStart) && configintlevel > 2) { w.Write(" TIMER : Timer Start time - "); w.WriteLine(" AT {0} :: {1} ", className, method); w.WriteLine("{0}", message); } //If the log level is set for QUERY TIMER else if (isNumeric && (level == logLevel.TimerEnd) && configintlevel > 2) { w.Write(" TIMER : Timer End time - "); w.WriteLine(" AT {0} :: {1} ", className, method); w.WriteLine("{0}", message); } w.Flush(); w.Close(); } } catch (Exception ex) { var stackTrace = new StackTrace(ex, true); var line = stackTrace.GetFrame(0).GetFileLineNumber(); Logger.LogExceptions(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, ex.Message, line.ToString(), Logger.logLevel.Exception); } }
public static void LogMessage(string message, string fileName = Constants.constLoggerFileName, logLevel level = logLevel.Error, bool showDialog = false) { if (message.Length <= 0) { return; } if (fileName.Length <= 0 || !fileName.Contains(".")) { fileName = Constants.constLoggerFileName; } if (!File.Exists(fileName)) { using (StreamWriter sw = File.CreateText(fileName)) { sw.WriteLine("Logging a(n)" + level.ToString() + " on " + DateTime.Now.ToString()); sw.WriteLine("Message - " + message); sw.WriteLine(); sw.WriteLine(); } } else { using (StreamWriter sw = File.AppendText(fileName)) { sw.WriteLine("Logging " + level.ToString() + " on " + DateTime.Now.ToString()); sw.WriteLine("Message - " + message); sw.WriteLine(); sw.WriteLine(); } } if (showDialog) { MessageBoxImage img; if (level == logLevel.Error) { img = MessageBoxImage.Error; } else if (level == logLevel.Information) { img = MessageBoxImage.Information; } else { img = MessageBoxImage.Warning; } MessageBox.Show(message, "Message:", MessageBoxButton.OK, img); } }
=> Apply(new LogCreated(logLevel, message, clientId, LogId));
AddToLog(logLevel, String.Empty, data);
public MatrixSwitcher(string p_strName, string p_strCOM, string p_strIPAddress, string p_strCurrentSession, logLevel p_objLogLevel = logLevel.ErrorOnly) { SwitcherName = p_strName; SwitcherCOMPort = p_strCOM; SwitcherIPAddress = p_strIPAddress; myDB = new AutomationsEntities(); m_objLogger = new Logger(ref myDB, p_strCurrentSession, p_objLogLevel, "MatrixSwitcher()"); m_blnViaHTTP = true; //Serial Commands were not tested as of yet. Due to limitations, get requests will be used to control through the switchers admin UI m_lstAvailableCommands = new List <tblMatrixSwitcherCommand>(); if (m_blnViaHTTP) { //fill the list try { m_objLogger.logToMemory(string.Format("{0}: {1}: Generating the list of available commands via.", "New MatrixSwitcher()", SwitcherName)); m_lstAvailableCommands = (from commands in myDB.tblMatrixSwitcherCommands orderby commands.CommandID select commands).ToList(); m_objLogger.logToMemory(string.Format("{0}: Matrix Switcher Command Count: {1}", "New MatrixSwitcher()", m_lstAvailableCommands.Count())); } catch { } finally { m_objLogger.writePendingToDB(p_strFunctionName: "New MatrixSwitcher()"); } } }