示例#1
0
        void DebugMonitor_OnOutputDebugString(int pid, string text)
        {
            // Trim ending newline (if any) 
            if (text.EndsWith(Environment.NewLine))
                text = text.Substring(0, text.Length - Environment.NewLine.Length);

            // Replace dots by "middle dots" to preserve Logger namespace
            string processName = GetProcessName(pid);
            processName = processName.Replace('.', '·');

            LogMessage logMsg = new LogMessage();
            logMsg.Message = text;
            logMsg.LoggerName = String.Format("{0}.{1}", processName, pid);
            logMsg.Level = LogLevels.Instance[LogLevel.Debug];
            logMsg.ThreadName = pid.ToString();
            logMsg.TimeStamp = DateTime.Now;
            Notifiable.Notify(logMsg);
        }
示例#2
0
        /// <summary>
        /// Adds a new log message, synchronously.
        /// </summary>
        private void AddLogMessage(LogMessage logMsg)
        {
            if (_pauseLog)
            return;

              RemovedLogMsgsHighlight();

              _addedLogMessage = true;

              LogManager.Instance.ProcessLogMessage(logMsg);

              if (!Visible && UserSettings.Instance.NotifyNewLogWhenHidden)
            ShowBalloonTip("A new message has been received...");
        }
示例#3
0
        /// <summary>
        /// Transforms the notification into an asynchronous call.
        /// The actual method called to add a log message is 'AddLogMessage'.
        /// </summary>
        public void Notify(LogMessage logMsg)
        {
            //// InvokeRequired required compares the thread ID of the
              //// calling thread to the thread ID of the creating thread.
              //// If these threads are different, it returns true.
              //if (logListView.InvokeRequired)
              //{
              //    NotifyLogMsgCallback d = AddLogMessage;
              //    Invoke(d, new object[] { logMsg });
              //}
              //else
              //{
              //    AddLogMessage(logMsg);
              //}

              lock (_eventQueue)
              {
            _eventQueue.Enqueue(logMsg);
              }
        }
示例#4
0
        protected LogMessage CreateLogMessage(LoggingEvent logEvent)
        {
            LogMessage logMsg = new LogMessage();

			logMsg.LoggerName = _appendHostNameToLogger && logEvent.Properties.Contains(LoggingEvent.HostNameProperty)
        	                    	? String.Format("[Host: {0}].{1}", logEvent.Properties[LoggingEvent.HostNameProperty], logEvent.LoggerName)
        	                    	: logEvent.LoggerName;

        	logMsg.ThreadName = logEvent.ThreadName;
            logMsg.Message = logEvent.RenderedMessage;
            logMsg.TimeStamp = logEvent.TimeStamp;
            logMsg.Level = LogUtils.GetLogLevelInfo(logEvent.Level.Value);

            // Per LoggingEvent.ExceptionObject, the exception object is not serialized, but the exception 
            // text is available through LoggingEvent.GetExceptionString
            logMsg.ExceptionString = logEvent.GetExceptionString();

            // Copy properties as string
            foreach (DictionaryEntry entry in logEvent.Properties)
            {
                if ((entry.Key == null) || (entry.Value == null))
                    continue;

                logMsg.Properties.Add(entry.Key.ToString(), entry.Value.ToString());
            }

            return logMsg;
        }
示例#5
0
        public void LogEvents(LoggingEvent[] events)
        {
			if ((events == null) || (events.Length == 0) || (Notifiable == null))
                return;

			LogMessage[] logMsgs = new LogMessage[events.Length];
			for (int i = 0; i < events.Length; i++)
				logMsgs[i] = CreateLogMessage(events[i]);

			Notifiable.Notify(logMsgs);
        }
示例#6
0
        private void EventLogOnEntryWritten(object sender, EntryWrittenEventArgs entryWrittenEventArgs)
        {
            LogMessage logMsg = new LogMessage();

            logMsg.LoggerName = String.IsNullOrEmpty(entryWrittenEventArgs.Entry.Source)
                                    ? _baseLoggerName
                                    : String.Format("{0}.{1}", _baseLoggerName, entryWrittenEventArgs.Entry.Source);

            logMsg.Message = entryWrittenEventArgs.Entry.Message;
            logMsg.TimeStamp = entryWrittenEventArgs.Entry.TimeGenerated;
            logMsg.Level = LogUtils.GetLogLevelInfo(GetLogLevel(entryWrittenEventArgs.Entry.EntryType));
            logMsg.ThreadName = entryWrittenEventArgs.Entry.InstanceId.ToString();

            if (!String.IsNullOrEmpty(entryWrittenEventArgs.Entry.Category))
                logMsg.Properties.Add("Category", entryWrittenEventArgs.Entry.Category);
            if (!String.IsNullOrEmpty(entryWrittenEventArgs.Entry.UserName))
                logMsg.Properties.Add("User Name", entryWrittenEventArgs.Entry.UserName);

            Notifiable.Notify(logMsg);
        }
示例#7
0
        private void ParseFields(ref LogMessage logMsg, List<string> fields)
        {
            for (int i = 0; i < FieldList.Length; i++)
            {
                var fieldType = _fieldList[i];
                string fieldValue = fields[i];
                try
                {
                    switch (fieldType.Field)
                    {
                        case LogMessageField.SequenceNr:
                            logMsg.SequenceNr = ulong.Parse(fieldValue);
                            break;
                        case LogMessageField.LoggerName:
                            logMsg.LoggerName = fieldValue;
                            break;
                        case LogMessageField.Level:
                            logMsg.Level = LogLevels.Instance[(LogLevel) Enum.Parse(typeof (LogLevel), fieldValue)];
                            //if (logMsg.Level == null)
                            //    throw new NullReferenceException("Cannot parse string: " + fieldValue);
                            break;
                        case LogMessageField.Message:
                            logMsg.Message = fieldValue;
                            break;
                        case LogMessageField.ThreadName:
                            logMsg.ThreadName = fieldValue;
                            break;
                        case LogMessageField.TimeStamp:
                            DateTime time;
                            DateTime.TryParseExact(fieldValue, DateTimeFormat, null, DateTimeStyles.None, out time);
                            logMsg.TimeStamp = time;
                            break;
                        case LogMessageField.Exception:
                            logMsg.ExceptionString = fieldValue;
                            break;
                        case LogMessageField.CallSiteClass:
                            logMsg.CallSiteClass = fieldValue;
                            logMsg.LoggerName = logMsg.CallSiteClass;
                            break;
                        case LogMessageField.CallSiteMethod:
                            logMsg.CallSiteMethod = fieldValue;
                            break;
                        case LogMessageField.SourceFileName:
                            fieldValue = fieldValue.Trim("()".ToCharArray());
                            //Detect the Line Nr
                            var fileNameFields = fieldValue.Split(new[] {":"}, StringSplitOptions.None);
                            if (fileNameFields.Length == 3)
                            {
                                uint line;
                                var lineNrString = fileNameFields[2];
                                if (uint.TryParse(lineNrString, out line))
                                    logMsg.SourceFileLineNr = line;

                                var fileName = fieldValue.Substring(0, fieldValue.Length - lineNrString.Length - 1);
                                logMsg.SourceFileName = fileName;
                            }
                            else
                                logMsg.SourceFileName = fieldValue;
                            break;
                        case LogMessageField.SourceFileLineNr:
                            logMsg.SourceFileLineNr = uint.Parse(fieldValue);
                            break;
                        case LogMessageField.Properties:
                            logMsg.Properties.Add(fieldType.Property, fieldValue);
                            break;
                    }
                }
                catch (Exception ex)
                {
                    var sb = new StringBuilder();
                    foreach (var field in fields)
                    {
                        sb.Append(field);
                        sb.Append(Delimiter);
                    }

                    logMsg = new LogMessage
                                 {
                                     SequenceNr = 0,
                                     LoggerName = "Log2Console",
                                     Level = LogLevels.Instance[LogLevel.Error],
                                     Message = "Error Parsing Log Entry Line: " + sb,
                                     ThreadName = string.Empty,
                                     TimeStamp = DateTime.Now,
                                     ExceptionString = ex.Message + ex.StackTrace,
                                     CallSiteClass = string.Empty,
                                     CallSiteMethod = string.Empty,
                                     SourceFileName = string.Empty,
                                     SourceFileLineNr = 0,
                                 };
                    return;
                }
            }
        }
示例#8
0
        public void ProcessLogMessage(LogMessage logMsg)
        {
            // Check 1st in the global LoggerPath/Logger dictionary
            LoggerItem logger;
            logMsg.CheckNull();

            if (!_fullPathLoggers.TryGetValue(logMsg.LoggerName, out logger))
            {
                // Not found, create one
                logger = RootLoggerItem.GetOrCreateLogger(logMsg.LoggerName);
            }
            if (logger == null)
                throw new Exception("No Logger for this Log Message.");

            logger.AddLogMessage(logMsg);
        }
示例#9
0
        public LogMessageItem(LoggerItem parent, LogMessage logMsg)
        {
            Parent = parent;
            Message = logMsg;

            string parentName = Parent.Name;
            if ((Parent.Name == logMsg.ThreadName) && (Parent.Parent != null))
                parentName = Parent.Parent.Name;

            // Create List View Item
            var items = new ListViewItem.ListViewSubItem[UserSettings.Instance.ColumnConfiguration.Length];
            string toolTip = string.Empty;

            //Add all the Standard Fields to the ListViewItem
            for (int i=0; i<UserSettings.Instance.ColumnConfiguration.Length; i++)
            {
                items[i] = new ListViewItem.ListViewSubItem();
                var fieldType = UserSettings.Instance.ColumnConfiguration[i];

                switch (fieldType.Field)
                {
                    case LogMessageField.SequenceNr:
                        items[i].Text = logMsg.SequenceNr.ToString();
                        break;
                    case LogMessageField.LoggerName:
                        items[i].Text = logMsg.LoggerName;
                        break;
                    case LogMessageField.Level:
                        items[i].Text = logMsg.Level.Name;
                        break;
                    case LogMessageField.Message:
                        string msg = logMsg.Message.Replace("\r\n", " ");
                        msg = msg.Replace("\n", " ");
                        items[i].Text = msg;
                        toolTip = msg;
                        break;
                    case LogMessageField.ThreadName:
                        items[i].Text = logMsg.ThreadName;
                        break;
                    case LogMessageField.TimeStamp:
                        items[i].Text = logMsg.TimeStamp.ToString(UserSettings.Instance.TimeStampFormatString);
                        break;
                    case LogMessageField.Exception:
                        string exception = logMsg.ExceptionString.Replace("\r\n", " ");
                        exception = exception.Replace("\n", " ");
                        items[i].Text = exception;
                        break;
                    case LogMessageField.CallSiteClass:
                        items[i].Text = logMsg.CallSiteClass;
                        break;
                    case LogMessageField.CallSiteMethod:
                        items[i].Text = logMsg.CallSiteMethod;
                        break;
                    case LogMessageField.SourceFileName:
                        items[i].Text = logMsg.SourceFileName;
                        break;
                    case LogMessageField.SourceFileLineNr:
                        items[i].Text = logMsg.SourceFileLineNr.ToString();
                        break;
                    case LogMessageField.Properties:
                        break;
                }
            }

            //Add all the Properties in the Message to the ListViewItem
            foreach (var property in logMsg.Properties)
            {
                string propertyKey = property.Key;
                if (UserSettings.Instance.ColumnProperties.ContainsKey(propertyKey))
                {
                    int propertyColumnNumber = UserSettings.Instance.ColumnProperties[propertyKey];
                    if(propertyColumnNumber < items.Length)
                    {
                        items[propertyColumnNumber].Text = property.Value;
                    }
                }
            }

            Item = new ListViewItem(items, 0) {ToolTipText = toolTip, ForeColor = logMsg.Level.Color, Tag = this};
        }
示例#10
0
    /// <summary>
    /// Here we expect the log event to use the log4j schema.
    /// Sample:
    ///     <log4j:event logger="Statyk7.Another.Name.DummyManager" timestamp="1184286222308" level="ERROR" thread="1">
    ///         <log4j:message>This is an Message</log4j:message>
    ///         <log4j:properties>
    ///             <log4j:data name="log4jmachinename" value="remserver" />
    ///             <log4j:data name="log4net:HostName" value="remserver" />
    ///             <log4j:data name="log4net:UserName" value="REMSERVER\Statyk7" />
    ///             <log4j:data name="log4japp" value="Test.exe" />
    ///         </log4j:properties>
    ///     </log4j:event>
    /// </summary>
    /// 
    /// Implementation inspired from: http://geekswithblogs.net/kobush/archive/2006/04/20/75717.aspx
    /// 
    public static LogMessage ParseLog4JXmlLogEvent(XmlReader reader, string defaultLogger)
    {
      var logMsg = new LogMessage();

      reader.Read();
      if ((reader.MoveToContent() != XmlNodeType.Element) || (reader.Name != "log4j:event"))
        throw new Exception("The Log Event is not a valid log4j Xml block.");

      logMsg.LoggerName = reader.GetAttribute("logger");
      logMsg.Level = LogLevels.Instance[reader.GetAttribute("level")];
      logMsg.ThreadName = reader.GetAttribute("thread");

      long timeStamp;
      if (long.TryParse(reader.GetAttribute("timestamp"), out timeStamp))
        logMsg.TimeStamp = s1970.AddMilliseconds(timeStamp).ToLocalTime();

      int eventDepth = reader.Depth;
      reader.Read();
      while (reader.Depth > eventDepth)
      {
          if (reader.MoveToContent() == XmlNodeType.Element)
          {
              switch (reader.Name)
              {
                  case "log4j:message":
                      logMsg.Message = reader.ReadString();
                      break;

                  case "log4j:throwable":
                      logMsg.Message += Environment.NewLine + reader.ReadString();
                      break;

                  case "log4j:locationInfo":
                      logMsg.CallSiteClass = reader.GetAttribute("class");
                      logMsg.CallSiteMethod = reader.GetAttribute("method");
                      logMsg.SourceFileName = reader.GetAttribute("file");
                      uint sourceFileLine;
                      if (uint.TryParse(reader.GetAttribute("line"), out sourceFileLine))
                          logMsg.SourceFileLineNr = sourceFileLine;
                      break;
                  case "nlog:eventSequenceNumber":
                      ulong sequenceNumber;
                      if (ulong.TryParse(reader.ReadString(), out sequenceNumber))
                          logMsg.SequenceNr = sequenceNumber;
                      break;
                  case "nlog:locationInfo":
                      break;

                  case "log4j:properties":
                      reader.Read();
                      while (reader.MoveToContent() == XmlNodeType.Element
                             && reader.Name == "log4j:data")
                      {
                          string name = reader.GetAttribute("name");
                          string value = reader.GetAttribute("value");
                          if (name != null && name.ToLower().Equals("exceptions"))
                          {
                              logMsg.ExceptionString = value;
                          }
                          else
                          {
                              logMsg.Properties[name] = value;
                          }

                          reader.Read();
                      }

                      break;
              }
          }
          reader.Read();
      }

        return logMsg;
    }
示例#11
0
        internal LogMessageItem AddLogMessage(LogMessage logMsg)
        {
            LogMessageItem item = new LogMessageItem(this, logMsg);
            item.Enabled = Enabled;
            LogMessages.Add(item);

            // We may remove and add many items, disable the drawing one moment
            _logListView.BeginUpdate();

            // Limit the number of displayed messages if necessary
            if (UserSettings.Instance.MessageCycleCount > 0)
                RemoveExtraLogMessages(UserSettings.Instance.MessageCycleCount);

            // Set Previous item
            if (_logListView.Items.Count > 0)
                item.Previous =
                    _logListView.Items[_logListView.Items.Count - 1].Tag as LogMessageItem;

            // Message
            if (Enabled)
            {
                // Add it to the main list
                _logListView.Items.Add(item.Item);

                // Add to the corresponding if necessary
                if (UserSettings.Instance.GroupLogMessages && (Group != null))
                    Group.Items.Add(item.Item);

                // Force the item to be visible if necessary
                if (UserSettings.Instance.AutoScrollToLastLog)
                    item.Item.EnsureVisible();
            }

            // Hide the item is is not in range or doesn't match the current text search if any
            if (!IsItemToBeEnabled(item))
                DisableLogMessage(item);

            // Done!
            _logListView.EndUpdate();

            return item;
        }
示例#12
0
        public LogMessageItem(LoggerItem parent, LogMessage logMsg)
        {
            Parent = parent;
            Message = logMsg;

            string parentName = Parent.Name;
            if ((Parent.Name == logMsg.ThreadName) && (Parent.Parent != null))
                parentName = Parent.Parent.Name;

            // Create List View Item
            Item = new ListViewItem(logMsg.TimeStamp.ToString(UserSettings.Instance.TimeStampFormatString));
            Item.SubItems.Add(logMsg.Level.Name);
            Item.SubItems.Add(parentName);
            Item.SubItems.Add(logMsg.ThreadName);

            string msg = logMsg.Message.Replace("\r\n", " ");
            msg = msg.Replace("\n", " ");
            Item.SubItems.Add(msg);
            Item.ToolTipText = msg;

            Item.ForeColor = logMsg.Level.Color;
            Item.Tag = this;
        }
示例#13
0
        /// <summary>
        /// Db call to fetch records from log table
        /// </summary>
        /// <param name="_fieldList"></param>
        /// <param name="connectionString"></param>
        /// <param name="logTableName"></param>
        /// <returns></returns>
        public List<LogMessage> GetLoggerItems(FieldType[] _fieldList, string connectionString, string logTableName, int rowcount)
        {
            List<LogMessage> logMsgs = new List<LogMessage>();
            MySqlConnection connection = null;

            using (connection = this.DbConnect(connectionString))
            {
                if (connection == null)
                {
                    return null;
                }
                try
                {
                    MySqlCommand sqlCmd = connection.CreateCommand();
                    sqlCmd.CommandText = GetMySqlAllLoggerStatement(_fieldList, logTableName, rowcount);
                    MySqlDataAdapter da = new MySqlDataAdapter();
                    da.SelectCommand = sqlCmd;
                    DataSet ds = new DataSet();

                    connection.Open();
                    da.Fill(ds);
                    connection.Close();

                    if (ds.Tables[1].Rows.Count > 0)
                    {
                        foreach (DataRow row in ds.Tables[1].Rows)
                        {
                            LogMessage logmsg = new LogMessage();
                            foreach (FieldType item in _fieldList)
                            {
                                ParseFields(ref logmsg, Convert.ToString(row[item.Name]), item);
                            }
                            logMsgs.Add(logmsg);
                        }
                    }
                }
                catch (MySqlException exceptionSQL)
                {
                    connection.Close();
                    ApplicationException exception1;
                    if (exceptionSQL.Message.Contains("Invalid column name"))
                    {
                        exception1 = new ApplicationException("Please map log table columns name properly", exceptionSQL);
                    }
                    else
                    {
                        exception1 = new ApplicationException("Error reading logrows from database collecting all logger names", exceptionSQL);
                    }
                    throw exception1;
                }
                catch (Exception exception)
                {
                    //Column '' does not belong to table Table.
                    connection.Close();
                    ApplicationException exception2;
                    if (exception.Message.Contains("does not belong to table Table"))
                    {
                        exception2 = new ApplicationException("Please map log table columns name properly", exception);
                    }
                    else
                        exception2 = new ApplicationException("Error reading logrows from database collecting all logger names", exception);
                    throw exception2;
                }
            }
            return logMsgs;
        }
示例#14
0
 /// <summary>
 /// To parse data according to database fields
 /// </summary>
 /// <param name="logMsg"></param>
 /// <param name="dataValue"></param>
 /// <param name="valueType"></param>
 private void ParseFields(ref LogMessage logMsg, string dataValue, FieldType valueType)
 {
     try
     {
         switch (valueType.Field)
         {
             case LogMessageField.SequenceNr:
                 logMsg.SequenceNr = ulong.Parse(dataValue);
                 break;
             case LogMessageField.LoggerName:
                 logMsg.LoggerName = dataValue;
                 break;
             case LogMessageField.Level:
                 //logMsg.Level = LogLevels.Instance[(Log2Console.Log.LogLevel)Enum.Parse(typeof(Log2Console.Log.LogLevel), dataValue)];
                 logMsg.Level = LogLevels.Instance[dataValue];
                 break;
             case LogMessageField.Message:
                 logMsg.Message = dataValue;
                 break;
             case LogMessageField.ThreadName:
                 logMsg.ThreadName = dataValue;
                 break;
             case LogMessageField.TimeStamp:
                 DateTime time = Convert.ToDateTime(dataValue);
                 logMsg.TimeStamp = time;
                 break;
             case LogMessageField.Exception:
                 logMsg.ExceptionString = dataValue;
                 break;
             case LogMessageField.Properties:
                 logMsg.Properties[valueType.Name] = dataValue;
                 break;
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
示例#15
0
        /// <summary>
        /// Function to parse flat log file
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public override List<LogMessage> Parse(Log2Console.Configuration.Configuration config)
        {
            ConfigurationSettings setting = config.Configurations;//Get parameters which has been passed from Receiver.
            string line;
            var sb = new StringBuilder();
            List<LogMessage> logMsgs = new List<LogMessage>();

            /////////////////////////////////////////////////////////////
            //To get conversion pattern string arrayk
            LoggerFormatParser formatparser = new LoggerFormatParser();
            formatparser.ParseLog4J4NetFormatString(setting.ConversionPattern);
            ////////////////////////////////////////////////////////////

            while ((line = setting.FileReader.ReadLine()) != null)
            {
                if (!string.IsNullOrEmpty(line))
                {
                    int errorCount = 0;
                    LogMessage logMsg = new LogMessage();
                    try
                    {
                        //////////////////////////////////////////////////////
                        foreach (var item in formatparser.ColInfoList)
                        {
                            string[] stringSeparators = new string[] { item.TrailingSeparator };
                            string separator = stringSeparators[0].ToString();
                            string[] strResult = new string[0];
                            string dataValue;

                            strResult = line.Split(stringSeparators, StringSplitOptions.None);
                            if (!string.IsNullOrEmpty(item.FormatString))//for datetime string cut value exactly same as formatstring instead separator
                            {
                                if (strResult[0].Length <= 10)
                                    dataValue = strResult[0] + separator + strResult[1];
                                else
                                    dataValue = strResult[0];
                            }
                            else
                            {

                                dataValue = strResult[0];
                            }


                            errorCount = LoggerFormatParser.SetLogMsgObj(dataValue, item.Header.ToLower(), logMsg, item.FormatString);//Get logMsg object filled.
                            if (errorCount > 0)//Case of stack trace where next complete line is the part of previous message.
                                break;

                            int count = 0;

                            if (!string.IsNullOrEmpty(line))
                            {
                                if (!string.IsNullOrEmpty(item.FormatString))//for datetime string cut exactly same as formatstring
                                {
                                    count = (item.FormatString + separator).Length;
                                    line = line.Remove(0, count);
                                }
                                else if (item.MinLength > 0)//case %-5level, where length is defined for level column value is 5
                                {
                                    count = item.MinLength + separator.Length;
                                    line = line.Remove(0, count);
                                }
                                else
                                    line = line.Replace(strResult[0] + separator, "");//Simple case where we need to cut already processed area from text line
                            }
                        }
                        //////////////////////////////////////////////////////
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    if (errorCount > 0)//Case of stack trace where next complete line is the part of previous message.
                        logMsgs[logMsgs.Count - 1].Message += Environment.NewLine + line;//Append this line into previous message.
                    else
                        logMsgs.Add(logMsg);
                }
            }

            return logMsgs;
        }
示例#16
0
        /// <summary>
        /// Transforms the notification into an asynchronous call.
        /// The actual method called to add log messages is 'AddLogMessages'.
        /// </summary>
        public void Notify(LogMessage[] logMsgs)
        {
            //// InvokeRequired required compares the thread ID of the
            //// calling thread to the thread ID of the creating thread.
            //// If these threads are different, it returns true.
            //if (logListView.InvokeRequired)
            //{
            //    NotifyLogMsgsCallback d = AddLogMessages;
            //    Invoke(d, new object[] { logMsgs });
            //}
            //else
            //{
            //    AddLogMessages(logMsgs);
            //}

            //Code to add all columns values into message column.
            Type type = typeof(LogMessage);
            FieldInfo[] fields = type.GetFields();

            foreach (LogMessage logMsg in logMsgs)
            {
                foreach (FieldInfo field in fields)
                {
                    string value = string.Empty;
                    if (field.Name.Equals("Properties"))
                    {
                        var values = field.GetValue(logMsg);
                        Dictionary<string, string> con = (Dictionary<string, string>)values;
                        foreach (var item in con)
                        {
                            value += (item.Value + "  :: ");
                        }
                    }
                    else if (field.Name.Equals("Level"))
                    {
                        if (field.GetValue(logMsg) != null)
                            value = Convert.ToString(((LogLevelInfo)(field.GetValue(logMsg))).Name);
                    }
                    else
                        value = Convert.ToString(field.GetValue(logMsg));

                    if (!string.IsNullOrEmpty(value) && field.Name != "Message")
                        logMsg.Message += ("  :: " + value);
                }
            }

            lock (_eventQueue)
            {
                foreach (var logMessage in logMsgs)
                {
                    _eventQueue.Enqueue(logMessage);
                }
            }
        }
示例#17
0
        /// <summary>
        /// To Fill logMsg object from text line
        /// </summary>
        /// <param name="value"></param>
        /// <param name="displayName"></param>
        /// <param name="logMsg"></param>
        /// <param name="formatString"></param>
        public static int SetLogMsgObj(string value, string displayName, LogMessage logMsg, string formatString)
        {
            try
            {
                switch (displayName)
                {
                    case "message":
                    case "m":
                        logMsg.Message = value;
                        break;

                    case "level":
                        logMsg.Level = LogLevels.Instance[value];
                        break;

                    case "logger":
                        logMsg.LoggerName = value;
                        break;

                    case "date":
                    case "d":
                    case "longdate":
                    case "utcdate":
                        DateTime dateVal;
                        if (formatString.Contains("fff"))
                        {
                            IFormatProvider culture = new CultureInfo("en-US", true);
                            dateVal = DateTime.ParseExact(value, formatString, culture);
                        }
                        else
                        {
                            dateVal = Convert.ToDateTime(value);
                        }

                        logMsg.TimeStamp = dateVal;
                        break;

                    case "thread":
                    case "threadid":
                        logMsg.ThreadName = value;
                        break;
                }
                return 0;
            }
            catch (FormatException ex)
            {
                if (ex.Message.ToLower().Contains("string was not recognized as a valid datetime."))
                    return 1;//Case where stack tarce kind of data inside message field.
                else
                    throw;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#18
0
        private void ReadFile()
        {
            if (!File.Exists(_fileToWatch))
            {
                return;
            }

            StreamReader fileReader;
            using (fileReader = new StreamReader(new FileStream(_fileToWatch, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {

                if (fileReader.BaseStream.Length == _lastFileLength)
                    return;

                if (fileReader.BaseStream.Length < _lastFileLength)
                {
                    //Log file has been trucated/deleted/renamed
                    _lastFileLength = 0;
                }

                // Seek to the last file length
                fileReader.BaseStream.Seek(_lastFileLength, SeekOrigin.Begin);

                // Get last added lines
                string line;
                var sb = new StringBuilder();
                List<LogMessage> logMsgs = new List<LogMessage>();

                while ((line = fileReader.ReadLine()) != null)
                {
                    if (_fileFormat == FileFormatEnums.Flat)
                    {
                        LogMessage logMsg = new LogMessage();

                        logMsg.LoggerName = _fullLoggerName;
                        logMsg.ThreadName = "NA";
                        logMsg.Message = line;
                        logMsg.TimeStamp = DateTime.Now;
                        logMsg.Level = LogLevels.Instance[LogLevel.Info];

                        logMsgs.Add(logMsg);
                    }
                    else
                    {
                        sb.Append(line);

                        // This condition allows us to process events that spread over multiple lines
                        if (line.Contains("</log4j:event>"))
                        {
                            LogMessage logMsg = ReceiverUtils.ParseLog4JXmlLogEvent(sb.ToString(), _fullLoggerName);
                            logMsgs.Add(logMsg);
                            sb = new StringBuilder();
                        }
                    }
                }

                // Notify the UI with the set of messages
                Notifiable.Notify(logMsgs.ToArray());

                // Update the last file length
                _lastFileLength = fileReader.BaseStream.Position;
            }
        }
示例#19
0
        private void ReadFile()
        {
            if ((_fileReader == null))
                return;

            if (_fileReader.BaseStream.Position > _fileReader.BaseStream.Length)
            {
                _fileReader.BaseStream.Seek(0, SeekOrigin.Begin);
                _fileReader.DiscardBufferedData();
            }

            // Get last added lines
            var logMsgs = new List<LogMessage>();
            List<string> fields;

            while ((fields = ReadLogEntry()) != null)
            {
                var logMsg = new LogMessage {ThreadName = string.Empty};

                if (fields.Count == FieldList.Length)
                {
                    ParseFields(ref logMsg, fields);
                    logMsgs.Add(logMsg);
                }
            }

            // Notify the UI with the set of messages
            Notifiable.Notify(logMsgs.ToArray());
        }
示例#20
0
        /// <summary>
        /// 
        /// </summary>
        private void Start()
        {
            _queue = new MessageQueue(this.QueueName);

            _queue.ReceiveCompleted += delegate(Object source, ReceiveCompletedEventArgs asyncResult)
            {
                try
                {
                    // End the asynchronous receive operation.
                    Message m = ((MessageQueue)source).EndReceive(asyncResult.AsyncResult);

                    if (Notifiable != null)
                    {
                        string loggingEvent = System.Text.Encoding.ASCII.GetString(((MemoryStream)m.BodyStream).ToArray());
                        LogMessage logMsg = ReceiverUtils.ParseLog4JXmlLogEvent(loggingEvent, "MSMQLogger");
                        logMsg.LoggerName = string.Format("{0}_{1}", QueueName.TrimStart('.'), logMsg.LoggerName);
                        Notifiable.Notify(logMsg);
                    }

                    if (this.BulkProcessBackedUpMessages)
                    {
                        Message[] all = ((MessageQueue) source).GetAllMessages();
                        if (all.Length > 0)
                        {
                            int numberofmessages = all.Length > 1000 ? 1000 : all.Length;

                            LogMessage[] logs = new LogMessage[numberofmessages];

                            for (int i = 0; i < numberofmessages; i++)
                            {
                                Message thisone = ((MessageQueue) source).Receive();

                                string loggingEvent =
                                    System.Text.Encoding.ASCII.GetString(((MemoryStream) thisone.BodyStream).ToArray());
                                LogMessage logMsg = ReceiverUtils.ParseLog4JXmlLogEvent(loggingEvent, "MSMQLogger");
                                logMsg.LoggerName = string.Format("{0}_{1}", QueueName.TrimStart('.'), logMsg.LoggerName);
                                logs[i] = logMsg;
                            }

                            Notifiable.Notify(logs);
                        }
                    }

                    ((MessageQueue)source).BeginReceive();
                }
                catch (MessageQueueException)
                {
                    // Handle sources of MessageQueueException.
                }
            };

            _queue.BeginReceive();
        }
示例#21
0
        private void ReadFile()
        {
            if ((_fileReader == null) || (_fileReader.BaseStream.Length == _lastFileLength))
                return;

            // Seek to the last file length
            _fileReader.BaseStream.Seek(_lastFileLength, SeekOrigin.Begin);

            // Get last added lines
            string line;
            var sb = new StringBuilder();
            List<LogMessage> logMsgs = new List<LogMessage>();
            
            while ((line = _fileReader.ReadLine()) != null)
            {
                if (_fileFormat == FileFormatEnums.Flat)
                {
                    LogMessage logMsg = new LogMessage();
                    logMsg.LoggerName = _fullLoggerName;
                    logMsg.ThreadName = "NA";
                    logMsg.Message = line;
                    logMsg.TimeStamp = DateTime.Now;
                    logMsg.Level = LogLevels.Instance[LogLevel.Info];

                    logMsgs.Add(logMsg);
                }
                else
                {
                    sb.Append(line);

                    // This condition allows us to process events that spread over multiple lines
                    if (line.Contains("</log4j:event>"))
                    {
                        LogMessage logMsg = ReceiverUtils.ParseLog4JXmlLogEvent(sb.ToString(), _fullLoggerName);
                        logMsgs.Add(logMsg);
                        sb = new StringBuilder();
                    }
                }
            }

            // Notify the UI with the set of messages
            Notifiable.Notify(logMsgs.ToArray());

            // Update the last file length
            _lastFileLength = _fileReader.BaseStream.Position;
        }
示例#22
0
        /// <summary>
        /// Here we expect the log event to use the log4j schema.
        /// Sample:
        ///     <log4j:event logger="Statyk7.Another.Name.DummyManager" timestamp="1184286222308" level="ERROR" thread="1">
        ///         <log4j:message>This is an Message</log4j:message>
        ///         <log4j:properties>
        ///             <log4j:data name="log4jmachinename" value="remserver" />
        ///             <log4j:data name="log4net:HostName" value="remserver" />
        ///             <log4j:data name="log4net:UserName" value="REMSERVER\Statyk7" />
        ///             <log4j:data name="log4japp" value="Test.exe" />
        ///         </log4j:properties>
        ///     </log4j:event>
        /// </summary>
        /// 
        /// Implementation inspired from: http://geekswithblogs.net/kobush/archive/2006/04/20/75717.aspx
        /// 
        public static LogMessage ParseLog4JXmlLogEvent(XmlReader reader, string defaultLogger)
        {
            var logMsg = new LogMessage();

              reader.Read();
              if ((reader.MoveToContent() != XmlNodeType.Element) || (reader.Name != "log4j:event"))
            throw new Exception("The Log Event is not a valid log4j Xml block.");

              logMsg.LoggerName = reader.GetAttribute("logger");
              logMsg.Level = LogLevels.Instance[reader.GetAttribute("level")];
              logMsg.ThreadName = reader.GetAttribute("thread");

              long timeStamp;
              if (long.TryParse(reader.GetAttribute("timestamp"), out timeStamp))
            logMsg.TimeStamp = s1970.AddMilliseconds(timeStamp).ToLocalTime();

              int eventDepth = reader.Depth;
              reader.Read();
              while (reader.Depth > eventDepth)
              {
            if (reader.MoveToContent() == XmlNodeType.Element)
            {
              switch (reader.Name)
              {
            case "log4j:message":
              logMsg.Message = reader.ReadString();
              break;

            case "log4j:throwable":
              logMsg.Message += Environment.NewLine + reader.ReadString();
              break;

            case "log4j:locationInfo":
              break;

            case "log4j:properties":
              reader.Read();
              while (reader.MoveToContent() == XmlNodeType.Element
                     && reader.Name == "log4j:data")
              {
                string name = reader.GetAttribute("name");
                string value = reader.GetAttribute("value");
                logMsg.Properties[name] = value;
                reader.Read();
              }
              break;
              }
            }
            reader.Read();
              }

              return logMsg;
        }