public static void Output(string Message, ErrorLevel Level)
 {
     if (Level >= ErrorLevel.Error)
         ErrorStream.WriteLine("{0}: {1}", Level.ToString(), Message);
     else
         Console.WriteLine("{0}: {1}", Level.ToString(), Message);
 }
Ejemplo n.º 2
0
        public static void Log(object message, Type type, ErrorLevel logType = ErrorLevel.Info)
        {
            switch (logType)
            {
            case ErrorLevel.Info:
            {
                _logger.Info(message);

                Console.WriteLine($"[{logType.ToString()}] {message}");
                break;
            }

            case ErrorLevel.Warning:
            {
                _logger.Warn(message);
#if DEBUG
                lock (_consoleSync)
                {
                    Console.ForegroundColor = ConsoleColor.DarkMagenta;
                    Console.WriteLine($"[{logType.ToString()}] {message}");
                    Console.ResetColor();
                }

                Resources.Sentry.Report(message.ToString(), type, logType);
#endif
                break;
            }

            case ErrorLevel.Error:
            {
                _logger.Error(message);
#if DEBUG
                lock (_consoleSync)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"[{logType.ToString()}] {message}");
                    Console.ResetColor();
                }

                Resources.Sentry.Report(message.ToString(), type, logType);
#endif
                break;
            }

            case ErrorLevel.Debug:
            {
#if DEBUG
                _logger.Debug(message);

                lock (_consoleSync)
                {
                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    Console.WriteLine($"[{logType.ToString()}] {message}");
                    Console.ResetColor();
                }
#endif
                break;
            }
            }
        }
 public static void Output(string Message, ErrorLevel Level)
 {
     if (Level >= ErrorLevel.Error)
     {
         ErrorStream.WriteLine("{0}: {1}", Level.ToString(), Message);
     }
     else
     {
         Console.WriteLine("{0}: {1}", Level.ToString(), Message);
     }
 }
Ejemplo n.º 4
0
        public static void Write(ErrorLevel level, string message)
        {
            // show stack
            var t = new StackTrace(true);

            ErrorLog.GetDefault(null).Log(new Error(new Exception(string.Concat(level.ToString(), ":", message, ":", t.ToString()))));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Write the preliminary log text, including timestamp and version info.
        /// </summary>
        /// <param name="sw">The stream to write the log to.</param>
        /// <param name="title">Title associated with log.</param>
        /// <param name="message">Message to be included with log.</param>
        /// <param name="severity">The severity of the error being logged.</param>
        private void WriteHeader(StreamWriter sw, string label, string message, ErrorLevel severity)
        {
            int count = 0;

            sw.WriteLine("{0:f}", DateTime.Now);
            sw.WriteLine(Assembly.GetCallingAssembly().FullName);
            sw.WriteLine("Error severity level: {0}", severity.ToString());
            sw.WriteLine();

            if ((label != null) && (label != ""))
            {
                sw.WriteLine(label);
                count++;
            }

            if ((message != null) && (message != ""))
            {
                sw.WriteLine(string.Format("Message: {0}", message));
                count++;
            }

            if (count > 0)
            {
                sw.WriteLine();
            }
        }
Ejemplo n.º 6
0
 private static void RecordTelemetryInfo(ErrorLevel errorLevel, string message, Dictionary <string, object> preppedData = null)
 {
     if (Enum.TryParse(errorLevel.ToString(), out TelemetryLevel telemetryLevel))
     {
         var telemetry = new Telemetry(TelemetrySource.Client, telemetryLevel, new LogTelemetry(message, preppedData));
         TelemetryCollector.Instance.Capture(telemetry);
     }
 }
Ejemplo n.º 7
0
        static void NotifyUser(string message, ErrorLevel errlvl)
        {
            var oldColor = Console.ForegroundColor;

            Console.ForegroundColor = ErrLevelColors[errlvl];
            Console.Write($"[{errlvl.ToString().ToUpper()}] ({DateTime.Now}) {message}");
            Console.ForegroundColor = oldColor;
        }
Ejemplo n.º 8
0
 private void PrintWarning(string expectation, params object[] args)
 {
     Console.WriteLine("{0}: Line {1}: Field <{2}> {4} {5}, but is <{3}>.", errorLevel.ToString().ToUpper(),
                       Program.LineNumber,
                       fieldName,
                       fieldValue,
                       GetExpectationKind(), string.Format(expectation, args));
 }
Ejemplo n.º 9
0
        public string Validate(Record rec)
        {
            if (rec.firstname.Any(c => char.IsDigit(c)))
            {
                return($"{errorLevel.ToString()}: 'Name' contains numeric characters. ");
            }

            return(null);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Method to log all operations
        /// </summary>
        /// <param name="operationData">Which operation is the error being raised from</param>
        /// <param name="dataCenter">Which dataCenter the current code runs on</param>
        /// <param name="operationResult">Defines what is the result of the operation</param>
        /// <param name="errorLevel">Error level - Critical, Error, Warning or None</param>
        /// <param name="startTime">Start time</param>
        /// <param name="propertyBag">A dictionary of values that provide context on the operation</param>
        /// <param name="message">A brief explanation of the result</param>
        /// <param name="errorSignature">A succinct error signature to identify that error and allow aggregation on that error type</param>
        /// <param name="durationMs">Time in milliseconds to complete operation</param>
        /// <param name="exception">Exception that contains exception stack trace and error message</param>
        /// <param name="httpStatusCode">Status code</param>
        /// <param name="tenantId">Tenant id</param>
        public void LogOperation(
            OperationData operationData,
            string dataCenter,
            OperationResult operationResult,
            ErrorLevel errorLevel,
            DateTime startTime,
            IDictionary <string, object> propertyBag,
            string message,
            string errorSignature,
            int durationMs,
            string exception      = "",
            string httpStatusCode = "",
            string tenantId       = "")
        {
            if (string.IsNullOrWhiteSpace(tenantId))
            {
                tenantId = this.requestData.TenantId;
            }

            string correlationId = this.requestData.CorrelationId;
            string trafficSource = this.requestData.TrafficSource;

            if (this.eventSource.IsEnabled())
            {
                // The member names are used as Geneva event schema.
                // You can add more properties freely, but a name changing can cause Geneva operation logging to stop working.
                var data = new
                {
                    errorLevel     = errorLevel.ToString(),
                    result         = operationResult.ToString(),
                    service        = this.service,
                    component      = operationData.Component,
                    operationName  = operationData.OperationName,
                    dataCenter     = dataCenter,
                    durationMs     = durationMs,
                    errorSignature = errorSignature,
                    message        = message,
                    propertyBag    = propertyBag.ToJsonString(),
                    tenantId       = tenantId,
                    correlationId  = correlationId,
                    startTime      = startTime,
                    exception      = exception,
                    version        = this.version,
                    httpStatusCode = httpStatusCode,
                    trafficSource  = trafficSource,
                };

                this.eventSource.Write(
                    EtwEventNames.TraceOperationEventName,
                    new EventSourceOptions {
                    Level = EventLevel.Informational
                },
                    data);
            }

            Debug.WriteLine($"Operation: {operationData.OperationName}. Result: {operationResult}");
        }
Ejemplo n.º 11
0
        private XElement CreateStepsHeader()
        {
            var steps = XElement.Parse("<AutoX.Steps />");

            steps.SetAttributeValue(Constants.ON_ERROR, ErrorLevel.ToString());
            steps.SetAttributeValue(Constants.INSTANCE_ID, InstanceId);
            steps.SetAttributeValue(Constants._ID, GUID);
            return(steps);
        }
Ejemplo n.º 12
0
        public static void WriteErrorHistory(ErrorLevel errorLevel, string reason)
        {
            ErrorHistory info = new ErrorHistory();

            info.LEVEL  = errorLevel.ToString();
            info.REASON = reason;

            OutputMart.Instance.ErrorHistory.Add(info);
        }
Ejemplo n.º 13
0
 private static void WriteInLogFile(FileMode fileMode, string filePath, ErrorLevel errorLevel, string message, Exception ex)
 {
     using (var stream = new FileStream(filePath, fileMode))
     using (var stringWriter = new StreamWriter(stream))
     {
         stringWriter.WriteLine("====================Begin Error====================");
         stringWriter.WriteLine("Error level: " + errorLevel.ToString());
         stringWriter.WriteLine("Message from app: " + message);
         stringWriter.WriteLine("Exception: " + ex.ToString());
         stringWriter.WriteLine("Time: " + DateTime.UtcNow);
         stringWriter.WriteLine("====================End Error====================");
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Common logger
        /// </summary>
        /// <param name="message"></param>
        /// <param name="exception"></param>
        /// <param name="source"></param>
        /// <param name="level"></param>
        protected virtual void CommonLogger(string message, Exception exception, Type source, ErrorLevel level)
        {
            if (IsLoggable(level))
            {
                logs.AppendLine(string.Format("{0}: {1} {2} at {3}", level.ToString(), message ?? "", source?.FullName ?? "", DateTime.Now.ToString()));

                if (exception != null)
                {
                    logs.AppendLine(string.Format("Exception Details: {0}", exception.ToString()));
                }

                logs.AppendLine("###########" + Environment.NewLine);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Handle the actual recording of the information.
        ///
        /// This is the point where we can change how the message is handled
        /// </summary>
        /// <param name="level">Level of message</param>
        /// <param name="text">Text of message</param>
        /// <param name="request">Request that is currently being processed</param>
        /// <param name="exceptionObject">Exception that caused the event (if any)</param>
        /// <param name="caller">Method that generated this message</param>
        /// <param name="sourceFile">Soure file that generated this message</param>
        /// <param name="lineNumber">Source file line number that generated this message</param>
        private static void HandleMessage(
            ErrorLevel level,
            string text,
            HttpRequest request,
            Exception exceptionObject,
            string caller,
            string sourceFile,
            int lineNumber)
        {
            string formattedMessage;

            if (string.IsNullOrEmpty(caller) || string.IsNullOrEmpty(sourceFile))
            {
                formattedMessage = $"{level.ToString()}: {text}";
            }
            else
            {
                formattedMessage = $"{level.ToString()}: {text} in file: '{sourceFile}', Method: '{caller}', Line: {lineNumber}";
            }

            // TODO: Do the actual recording of the error here

            System.Diagnostics.Trace.WriteLine(formattedMessage);
        }
Ejemplo n.º 16
0
        public string Write(ILayout layout, IError error)
        {
            string format = layout.Format;

            DateTime   dateTime = error.DateTime;
            ErrorLevel level    = error.Level;
            string     message  = error.Message;

            string formattedMessage = String.Format(format,
                                                    dateTime.ToString(dateFormat, CultureInfo.InvariantCulture),
                                                    level.ToString(),
                                                    message);

            return(formattedMessage);
        }
Ejemplo n.º 17
0
        private void enqueueMessage(Exception ex, ErrorLevel errorLevel, string message)
        {
            string finalMessage = $"{DateTime.Now.ToUniversalTime().ToString()} {errorLevel.ToString()} {message}";

            if (ex != null)
            {
                finalMessage += Environment.NewLine + ex.StackTrace;
            }

            lock (messages)
            {
                messages.Enqueue(new Tuple <ErrorLevel, string>(errorLevel, finalMessage));
                Monitor.Pulse(messages);
            }
        }
        public override void Append(IError error)
        {
            string format = this.Layout.Format;

            DateTime   dateTime = error.DateTime;
            ErrorLevel level    = error.Level;
            string     message  = error.Message;

            string formattedMessage = String.Format(format,
                                                    dateTime.ToString(base.DateFormat, CultureInfo.InvariantCulture),
                                                    level.ToString(),
                                                    message);

            Console.WriteLine(formattedMessage);
            base.MessagesAppended++;
        }
Ejemplo n.º 19
0
        private bool LogIssue(Exception ex, string customErrorMsg, ErrorLevel errLevel)
        {
            bool retval = false;

            try
            {
                if (!string.IsNullOrEmpty(customErrorMsg))
                {
                    Console.WriteLine(errLevel.ToString() + ": " + customErrorMsg);
                }

                Console.WriteLine(ex);
            }
            catch (Exception err)
            {
                Console.Write("ERROR: ErrorLogger failed to log an error.  How?!?!" + err.ToString());
            }

            return(retval);
        }
Ejemplo n.º 20
0
        public static void LogError(Exception ex, ErrorLevel errorLevel, string message = null)
        {
            using (var db = new ApplicationDbContext())
            {
                try
                {
                    var errorTable = new ErrorTable
                    {
                        AppMessage = message,
                        ErrorLevel = errorLevel.ToString(),
                        ErrorTime = DateTime.Now,
                        ExceptionMessage = ex.ToString()
                    };

                    db.ErrorsTable.Add(errorTable);
                    db.SaveChanges();
                }
                finally
                {
                    string filePath = ConfigurationManager.AppSettings["errorFilePath"];
                    if (File.Exists(filePath))
                    {
                        FileInfo fileInfo = new FileInfo(filePath);
                        if(fileInfo.Length<100000)
                        {
                            WriteInLogFile(FileMode.Append, filePath, errorLevel, message, ex);
                        }
                        else
                        {
                            string bckpFileName = filePath.Remove(filePath.Length - 4);
                            bckpFileName = bckpFileName + ".bkp";
                            File.Move(filePath, bckpFileName);
                            WriteInLogFile(FileMode.OpenOrCreate, filePath, errorLevel, message, ex);
                        }
                    }
                    else
                        WriteInLogFile(FileMode.OpenOrCreate, filePath, errorLevel, message, ex);
                }
            }

        }
Ejemplo n.º 21
0
        public void ShowErrorDialog(string message, Exception e, ErrorLevel level)
        {
            System.Windows.Forms.MessageBoxButtons buttons = System.Windows.Forms.MessageBoxButtons.OK;
            System.Windows.Forms.MessageBoxIcon    icon    = System.Windows.Forms.MessageBoxIcon.Asterisk;

            switch (level)
            {
            case ErrorLevel.Comment:
                icon = System.Windows.Forms.MessageBoxIcon.Information;
                break;

            case ErrorLevel.Warning:
                icon = System.Windows.Forms.MessageBoxIcon.Warning;
                break;

            case ErrorLevel.Fatal:
                icon = System.Windows.Forms.MessageBoxIcon.Error;
                break;

            case ErrorLevel.Bug:
                icon = System.Windows.Forms.MessageBoxIcon.Hand;

                break;
            }

            StringBuilder builder = new StringBuilder();

            builder.AppendLine("An error has occured:");
            builder.AppendLine(message);

            if (e != null)
            {
                builder.AppendLine(e.Message);
                builder.AppendLine();
                builder.AppendLine(e.StackTrace);
            }

            System.Windows.Forms.MessageBox.Show
                (builder.ToString(), level.ToString(), buttons, icon);
        }
Ejemplo n.º 22
0
        public void Log(ErrorLevel level, Exception ex, string message, params object[] arg)
        {
            if (level == ErrorLevel.Debug)
            {
                return;
            }

            var tmp = new StringBuilder();

            tmp.Append(level.ToString("f")); // https://stackoverflow.com/a/32726578/6884

            if (ex != null)
            {
                tmp.Append(" ");
                tmp.Append(ex.Message);
            }

            tmp.Append(" ");
            tmp.AppendFormat(message, arg);

            this.messages.AddMessage(tmp.ToString());
        }
Ejemplo n.º 23
0
    //+-----------------------------------------------------------------------------------------------------
    //| l o g
    //+-----------------------------------------------------------------------------------------------------
    public static void log(string msg, ErrorLevel ErrorLevel)
    {
        string currentFilePath = HttpContext.Current.Server.MapPath("~") + "\\Logs\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
        string strText2Write   = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.000    ") +
                                 ErrorLevel.ToString().PadRight(20) +
                                 msg;

        try
        {
            lock (MyCriticalRessource)
            {
                using (StreamWriter sw = new StreamWriter(currentFilePath, true))
                {
                    sw.WriteLine(strText2Write);
                }
            }
        }
        catch
        {
            throw new Exception(" Error on Log File");
        }
    }
Ejemplo n.º 24
0
        public void Log(string errorType, string msg, string location, ErrorLevel level)
        {
            try
            {
                if (!this.enabled)
                {
                    return;
                }

                string ss = string.Format("\n{0} : {1} ���� {2} ����������:{3}��λ�ã�{4}", DateTime.Now.ToString(), level.ToString(), msg, errorType, location);

                this.FileLogger.Log(ss);
            }
            catch (Exception ee)
            {
                ee = ee;
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Writes a line to the log file, including where the original call came from, the file path and the line number
        /// </summary>
        /// <param name="message">The message you want to save to the file</param>
        /// <param name="errorLevel">The error level of the current write operation (INFO by default)</param>
        /// <param name="callingMethod">This should be ignored as the compiler sets this parameter at run time</param>
        /// <param name="callingFilePath">This should be ignored as the compiler sets this parameter at run time</param>
        /// <param name="callingFileLineNumber">This should be ignored as the compiler sets this parameter at run time</param>
        public void Write(string message, ErrorLevel errorLevel        = ErrorLevel.ErrInfo,
                          [CallerMemberName] string callingMethod      = "",
                          [CallerFilePath] string callingFilePath      = "",
                          [CallerLineNumber] int callingFileLineNumber = 0)
        {
            lock (_lockable)
            {
                // ReSharper disable once LocalizableElement
                System.IO.File.AppendAllText(_fullPath,
                                             $"[{DateTime.Now:dd-MM-yyyy_HH-mm-ss}] | [{callingMethod} @ Line {callingFileLineNumber} In {System.IO.Path.GetFileName(callingFilePath)} Thread {Thread.CurrentThread.ManagedThreadId}] | {errorLevel.ToString()} - {message}\r\n");
                if (_hasConsole)
                {
                    switch (errorLevel)
                    {
                    case ErrorLevel.ErrError:
                        Console.ForegroundColor = ConsoleColor.Red;
                        break;

                    case ErrorLevel.ErrInfo:
                    case ErrorLevel.ErrSuccess:
                        Console.ForegroundColor = ConsoleColor.White;
                        break;

                    case ErrorLevel.ErrWarning:
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        break;
                    }

                    // ReSharper disable once LocalizableElement
                    Console.WriteLine(
                        $"[{callingMethod} @ Line {callingFileLineNumber} In {System.IO.Path.GetFileName(callingFilePath)} Thread {Thread.CurrentThread.ManagedThreadId}] - {message}");
                }
            }
        }
Ejemplo n.º 26
0
        public static void Write(ErrorLevel errorLevel, string message)
        {
            var lex = new ExceptionWrapper(errorLevel.ToString(), new Exception(message));

            Write(lex);
        }
Ejemplo n.º 27
0
 public override string ToString()
 {
     return($"[ErroLevel={ErrorLevel.ToString("G")}] [Message={Message}]\n");
 }
Ejemplo n.º 28
0
 public static string ErrorToString(ErrorLevel header, string filename, int oneBasedLine, int oneBasedColumn, string msg)
 {
     return(ErrorToString_Internal(": " + header.ToString(), filename, oneBasedLine, oneBasedColumn, ": " + msg));
 }
Ejemplo n.º 29
0
        public string getFullErrorMessage()
        {
            //NavigableEndMustHaveName: - <Name of EReference> (EReference): Navigable end must have a role name - Fatal
            String outputForSingleRule = RuleID + ": - " + NameOfObject + "(" + TypeOfObject + "): " + ErrorOutput + " - " + ErrorLevel.ToString();

            return(outputForSingleRule);
        }
Ejemplo n.º 30
0
Archivo: Db.cs Proyecto: gerrkoff/Quest
 public static void InsertLog(ErrorLevel level, string text)
 {
     using (var con = new SqlConnection(Misc.ConnectionString))
     {
         con.Open();
         using (var command = new SqlCommand(InsertLogCommand, con))
         {
             command.Parameters.AddWithValue("@level", level.ToString());
             command.Parameters.AddWithValue("@text", text);
             command.ExecuteNonQuery();
         }
     }
 }
Ejemplo n.º 31
0
    /// <summary>
    /// 提供一個訊息回報的機制或者用以記錄一些資訊,取得特定的必要資料,讓未來取得更為方便的除錯工具。
    /// </summary>
    /// <param name="eType">這個回報訊息的類型。</param>
    /// <param name="clsFunction">請鍵入 MethodInfo.GetCurrentMethod()。</param>
    /// <param name="strMessage">要記錄的主要訊息。</param>
    /// <param name="eSaveItems">儲存寫檔的時機點。</param>
    /// <example>
    /// <code>
    /// private void Example()
    /// {
    ///		try
    ///		{
    ///			// ============
    ///			// 你要得動作
    ///			// ============
    ///
    ///			// 可以當成一般訊息紀錄使用 (很重要才紀錄)
    ///			XStatus.Report(XStatus.Type.Infomation, MethodInfo.GetCurrentMethod(),"想要紀錄的資訊");
    ///		}
    ///		catch(Exception ex)
    ///		{
    ///			XStatus.Report(XStatus.Type.Windows, MethodInfo.GetCurrentMethod(), XStatus.GetExceptionLine(ex));
    ///		}
    /// }
    /// </code>
    /// </example>
    public static void Report(Type eType, MethodBase clsFunction, string strMessage, ErrorLevel eErrorLevel = ErrorLevel.Alarm, SaveItems eSaveItems = SaveItems.Default)
    {
        string strClassName = (clsFunction != null) ? "{" + clsFunction.ReflectedType.Name + "}" : "{Unknow}";
        string functionName = (clsFunction != null) ? strClassName + "[" + clsFunction.Name + "]" : "Unknow[Unknow]";

        string strAllMessage = DateTime.Now.ToString(TIME_FORMAT) + ", " + eType.ToString() + ", " + functionName + " - " + strMessage;

        if (LogRecorder != null && SendLogRecorder)
        {
            LogRecorder.WriteLog(eErrorLevel.ToString() + "|" + strAllMessage);
        }
        else
        {
            if (g_strLogFolderPath.Length > 3)
            {
                string strFilePath = "";
                switch (g_eRecordType)
                {
                case RecordInterval.None:
                    strFilePath = g_strLogFolderPath;
                    break;

                case RecordInterval.Hours:
                    strFilePath = g_strLogFolderPath + "Log_" + DateTime.Now.ToString("yyyyMMddHH") + ".log";
                    break;

                case RecordInterval.Days:
                    strFilePath = g_strLogFolderPath + "Log_" + DateTime.Now.ToString("yyyyMMdd") + ".log";
                    break;
                }

                lock (g_oLockReserveMessage)
                {
                    try
                    {
                        if (eType != Type.Null)
                        {
                            // 在下面這段程式碼不直接呼叫其他功能函數,以免造成無窮回圈。
                            // 因為只有單行,所以在此允許插隊讓硬碟做此工作。
                            g_strReserveMessages.Add(strAllMessage);
                        }
                        lock (XFile.DiskLock)
                        {
                            switch (eSaveItems)
                            {
                            case SaveItems.Default:
                            case SaveItems.NoImmediate:
                                if (g_strReserveMessages.Count >= g_iReserveMessageThreshold)
                                {
                                    File.AppendAllLines(strFilePath, g_strReserveMessages);
                                    g_strReserveMessages.Clear();
                                }
                                break;

                            case SaveItems.Immediate:
                                File.AppendAllLines(strFilePath, g_strReserveMessages);
                                g_strReserveMessages.Clear();
                                break;
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }
        }
        lock (g_oLockReport)
        {
            try
            {
                LogMessage.Insert(0, strAllMessage);
                while (LogMessage.Count > 500)
                {
                    LogMessage.RemoveAt(500);
                }
            }
            catch
            {
            }
        }

        // Events Process (Callback function)
        //-------------------------------------------------------------------
        try
        {
            // 此順序由 Frank on 2014.10.9 排出,以危險性高低來做排序。
            switch (eType)
            {
            case Type.Motion:
                if (Status_MotionReport != null)
                {
                    Status_MotionReport(strAllMessage);
                }
                break;

            case Type.Robot:
                if (Status_RobotReport != null)
                {
                    Status_RobotReport(strAllMessage);
                }
                break;

            case Type.Device:
                if (Status_DeviceReport != null)
                {
                    Status_DeviceReport(strAllMessage);
                }
                break;

            case Type.IO:
                if (Status_IOReport != null)
                {
                    Status_IOReport(strAllMessage);
                }
                break;

            case Type.Communication:
                if (Status_CommunicationReport != null)
                {
                    Status_CommunicationReport(strAllMessage);
                }
                break;

            case Type.Vision:
                if (Status_VisionReport != null)
                {
                    Status_VisionReport(strAllMessage);
                }
                break;

            case Type.Procedure:
                if (Status_ProcedureReport != null)
                {
                    Status_ProcedureReport(strAllMessage);
                }
                break;

            case Type.Windows:
                if (Status_WindowsReport != null)
                {
                    Status_WindowsReport(strAllMessage);
                }
                break;

            case Type.Events:
                if (Status_EventsReport != null)
                {
                    Status_EventsReport(strAllMessage);
                }
                break;

            default:
                if (Status_AlarmReport != null)
                {
                    Status_AlarmReport(strAllMessage);
                }
                break;
            }
            if (Status_Changed != null)
            {
                Status_Changed(strAllMessage);
            }
        }
        catch
        {
            strAllMessage = DateTime.Now.ToString() + ", Events, {XStatus}[Report] - Callback function error.";
            g_strReserveMessages.Add(strAllMessage);    // 放到暫存區等待存檔。
            LogMessage.Insert(0, strAllMessage);        // 插入歷史紀錄的暫存區域。
        }
    }
Ejemplo n.º 32
0
        /// <summary>
        /// Write a string into the log file
        /// </summary>
        /// <param name="className">The class that returned the error</param>
        /// <param name="methodName">The method that returned the error</param>
        /// <param name="line">Theline of error</param>
        /// <param name="errorLevel">The error level</param>
        /// <param name="message">The error message</param>
        public static void Write(string className, string methodName, int line, ErrorLevel errorLevel, string message)
        {
            try
            {
                //get the log folder
                DirectoryInfo dir = new DirectoryInfo(ConfigUtils.LogFolder);

                //if log folder doesn't exist then create it
                if (!dir.Exists)
                {
                    dir.Create();
                }

                if (ConfigUtils.LogIsEnabled == true)
                {
                    using (StreamWriter sw = new StreamWriter(_fileName, true))
                    {
                        //write the string into the log file
                        sw.WriteLine(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss tt") + " " + errorLevel.ToString().ToUpper() + " MESSAGE:  "
                                     + message.Replace("\r", "").Replace("\n", "") + "  CLASS: " + className + "  METHOD: " + methodName + "  LINE: " + line);
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Write a string into the log file
        /// </summary>
        /// <param name="className">The class that returned the error</param>
        /// <param name="methodName">The method that returned the error</param>
        /// <param name="line">Theline of error</param>
        /// <param name="errorLevel">The error level</param>
        /// <param name="message">The error message</param>
        public static void Write(string className, string methodName, int line, ErrorLevel errorLevel, string message)
        {
            try
            {
                //get the log folder
                DirectoryInfo dir = new DirectoryInfo(ConfigUtils.LogFolder);

                //if log folder doesn't exist then create it
                if (!dir.Exists) dir.Create();

                if (ConfigUtils.LogIsEnabled == true)
                {
                    using (StreamWriter sw = new StreamWriter(_fileName, true))
                    {
                        //write the string into the log file
                        sw.WriteLine(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss tt") + " " + errorLevel.ToString().ToUpper() + " MESSAGE:  "
                            + message.Replace("\r", "").Replace("\n", "") + "  CLASS: " + className + "  METHOD: " + methodName + "  LINE: " + line);
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 34
0
 public static string ErrorToString(ErrorLevel header, IToken tok, string msg)
 {
     return ErrorToString_Internal(": " + header.ToString(), tok.filename, tok.line, tok.col, ": " + msg);
 }
Ejemplo n.º 35
0
 public static string ErrorToString(ErrorLevel header, IToken tok, string msg)
 {
     return(String.Format("{0}: {1}{2}", TokenToString(tok), header.ToString(), ": " + msg));
 }
Ejemplo n.º 36
0
 public static string ErrorToString(ErrorLevel header, string filename, int oneBasedLine, int oneBasedColumn, string msg)
 {
     return ErrorToString_Internal(": " + header.ToString(), filename, oneBasedLine, oneBasedColumn, ": " + msg);
 }
Ejemplo n.º 37
0
 public static string ErrorToString(ErrorLevel header, IToken tok, string msg)
 {
     return(ErrorToString_Internal(": " + header.ToString(), tok.filename, tok.line, tok.col, ": " + msg));
 }
Ejemplo n.º 38
0
        public override string ToString()
        {
            string levelString = _level.ToString().ToLower();

            return(_fileName + "(" + _lineNumber + "): " + levelString + " C" + _errorCode.ToString("0000") + ": " + _message);
        }