public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
        {
            lock (_sync)
            {
                if(Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null)) return;
                ConsoleColor color;
                switch (eventType)
                {
                    case TraceEventType.Error:
                        color = ConsoleColor.Red;
                        break;
                    case TraceEventType.Warning:
                        color = ConsoleColor.Yellow;
                        break;
                    case TraceEventType.Information:
                        color = ConsoleColor.Green;
                        break;
                    case TraceEventType.Verbose:
                        color = ConsoleColor.DarkCyan;
                        break;
                    default:
                        color = ConsoleColor.Gray;
                        break;
                }

                var eventTypeString = Enum.GetName(typeof (TraceEventType), eventType);
                    var message = source + " - " + eventTypeString + " > " + (args.Length > 0 ? string.Format(format, args): format);

                WriteColor(message + Environment.NewLine, color);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Writes the specified trace level, message and optional exception.
        /// </summary>
        /// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param>
        /// <param name="message">The trace message.</param>
        /// <param name="ex">The trace exception. This parameter is optional.</param>
        public void Trace(TraceLevel level, string message, Exception ex)
        {
            if (level == TraceLevel.Off)
            {
                return;
            }

            TraceEventCache eventCache = new TraceEventCache();
            TraceEventType traceEventType = GetTraceEventType(level);

            foreach (TraceListener listener in DiagnosticsTrace.Listeners)
            {
                if (!listener.IsThreadSafe)
                {
                    lock (listener)
                    {
                        listener.TraceEvent(eventCache, "Newtonsoft.Json", traceEventType, 0, message);
                    }
                }
                else
                {
                    listener.TraceEvent(eventCache, "Newtonsoft.Json", traceEventType, 0, message);
                }

                if (DiagnosticsTrace.AutoFlush)
                {
                    listener.Flush();
                }
            }
        }
        public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id,
                                       params object[] data)
        {
            if (this.Filter != null &&
                !this.Filter.ShouldTrace(eventCache, source, eventType, id, string.Empty, null, null, null))
                return;

            foreach (object obj in data)
            {
                if (obj is XPathNavigator)
                {
                    using (var reader = ((XPathNavigator)obj).ReadSubtree())
                    {
                        reader.MoveToContent();
                        if (reader.IsStartElement())
                            Console.WriteLine(XElement.ReadFrom(reader).ToString(SaveOptions.OmitDuplicateNamespaces));
                        else
                        {
                            Console.WriteLine("Unable to write Xml data.");
                        }
                    }
                }
                else
                {
                    Console.WriteLine(obj.ToString());
                }
            }
        }
 /// <summary>
 /// Forwards the trace request to the wrapped listener.
 /// </summary>
 /// <param name="eventCache">The context information.</param>
 /// <param name="source">The trace source.</param>
 /// <param name="severity">The severity.</param>
 /// <param name="id">The event id.</param>
 /// <param name="data">The objects to trace.</param>
 public override void TraceData(TraceEventCache eventCache, string source, TraceEventType severity, int id, params object[] data)
 {
     if ((this.Filter == null) || this.Filter.ShouldTrace(eventCache, source, severity, id, null, null, null, data))
     {
         this.innerListener.TraceData(eventCache, source, severity, id, data);
     }
 }
Ejemplo n.º 5
0
 public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
 {
     LogMessage msg = (LogMessage)data;
     byte[] buf = FormatMessage(string.Concat(msg.MessageAsText, "\n"));
     Stream.Write(buf, 0, buf.Length);													// Write message buffer
     Stream.Flush();
 }
Ejemplo n.º 6
0
		public override void TraceEvent (TraceEventCache eventCache, string source, TraceEventType severity, int id, string message)
		{
			if (HttpContext.Current == null || HttpContext.Current.Trace == null)
				return;

			HttpContext.Current.Trace.Write (source, message);
		}
Ejemplo n.º 7
0
 public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
 {
     if (args == null || args.Length == 0)
         Append(eventType, format);
     else
         Append(eventType, String.Format(format, args));
 }
Ejemplo n.º 8
0
        public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
        {
            if ((base.Filter == null) || base.Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null))
            {
                var prefix = source;
                var dotIndex = prefix.LastIndexOf('.');
                if (dotIndex != -1)
                    prefix = prefix.Substring(dotIndex + 1);

                switch (eventType)
                {
                    case TraceEventType.Critical:
                    case TraceEventType.Error:
                        Trace.TraceError("[{0}] {1}", prefix, message);
                        break;
                    case TraceEventType.Verbose:
                    case TraceEventType.Information:
                        Trace.TraceInformation("[{0}] {1}", prefix, message);
                        break;
                    case TraceEventType.Warning:
                        Trace.TraceWarning("[{0}] {1}", prefix, message);
                        break;
                    default:
                        break;
                }
            }
        }
 void PrintThreadId(TraceEventCache info)
 {
     Console.Out.Write("[");
     Console.Out.Write(info.ThreadId);
     Console.Out.Write("]");
     Console.Out.Write(" ");
 }
 protected override void TraceSimpleEvent(DateTime eventTime, Int32 threadId, TraceEventType eventType, String message, Int32 eventId, TraceEventCache eventCache, String source)
 {
     if (this._traceListener != null)
     {
         this._traceListener.TraceEvent(eventCache, source, eventType, eventId, message);
     }
 }
Ejemplo n.º 11
0
 public override sealed void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
 {
     if ((base.Filter == null) || base.Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null))
     {
         WriteTrace(eventCache, source, eventType, id, message, null, null);
     }
 }
 public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
 {
     try
     {
         var dict = message.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(part => part.Split('='))
            .ToDictionary(split => split[0], split => split[1]);
         string iid;
         if (dict.TryGetValue("iid", out iid))
         {
             string toWrite = string.Format("[{0} {1}] {2}", DateTime.Now, iid, dict["msg"]);
             base.WriteLine(toWrite);
         }
         else
         {
             string toWrite = string.Format("[{0}] {1}", DateTime.Now, dict["msg"]);
             base.WriteLine(toWrite);
         }
     }
     catch (Exception exception)
     {
         string toWrite = string.Format("Exception while parsing trace:  {0}\n\t", exception.Message, exception.StackTrace);
         base.WriteLine(toWrite);
     }
 }
Ejemplo n.º 13
0
        public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
        {
            if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null))
            {
                return;
            }

            var client = new SmtpClient(Settings.Default.SmtpServer)
                {
                    Credentials = new NetworkCredential(Settings.Default.SmtpUsername, Settings.Default.SmtpPassword),
                    EnableSsl = true
                };
            var body = string.Format(format, args);
            var firstLine = new StringReader(body).ReadLine();
            if (firstLine.Length > 100)
            {
                firstLine = firstLine.Substring(0, 97).Trim() + "...";
            }
            var msg = new MailMessage
                {
                    From = new MailAddress(Settings.Default.NotificationFrom, "FitBot"),
                    To = {Settings.Default.NotificationTo},
                    Subject = $"{eventType} - {firstLine}",
                    Body = body
                };
            client.Send(msg);
        }
		public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
		{
			tracedData = data;
			tracedSource = source;
			tracedEventType = eventType;
			entries.Add(data as LogEntry);
		}
Ejemplo n.º 15
0
        /// <summary>
        /// Writes the specified trace level, message and optional exception.
        /// </summary>
        /// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param>
        /// <param name="message">The trace message.</param>
        /// <param name="ex">The trace exception. This parameter is optional.</param>
        public void Trace(TraceLevel level, string message, Exception ex)
        {
            if (level == TraceLevel.Off)
                return;

            TraceEventCache eventCache = new TraceEventCache();
            TraceEventType traceEventType = GetTraceEventType(level);

            foreach (TraceListener listener in DiagnosticsTrace.Listeners)
            {
                if (!listener.IsThreadSafe)
                {
                    lock (listener)
                    {
                        listener.TraceEvent(eventCache, "Framework.Qlh.Common.Infrastructure.Json", traceEventType, 0, message);
                    }
                }
                else
                {
                    listener.TraceEvent(eventCache, "Framework.Qlh.Common.Infrastructure.Json", traceEventType, 0, message);
                }

                if (DiagnosticsTrace.AutoFlush)
                    listener.Flush();
            }
        }
Ejemplo n.º 16
0
		public void Write(LogEntry entry, Type filterListener)
		{
			Guard.ArgumentNotNull(entry, "entry");

			TraceEventCache manager = new TraceEventCache();

			foreach(TraceListener listener in this.Listeners)
			{
                bool lockTaken = false;
				try
				{                    
					if (!listener.IsThreadSafe)
					{
                        Monitor.Enter(sync, ref lockTaken);
					}
					if (filterListener == null ||
						filterListener == listener.GetType())
					{
						listener.TraceData(manager, string.Empty, entry.Severity, 0, entry);
						listener.Flush();
					}
				}
				finally
				{
                    if (!listener.IsThreadSafe && lockTaken)
					{
                        Monitor.Exit(sync);
					}
				}
			}
		}
Ejemplo n.º 17
0
 public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
 {
     if ((this.Filter == null) || this.Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null))
     {
         this.WriteLine(message);
     }
 }
Ejemplo n.º 18
0
 public override sealed void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data)
 {
     if ((base.Filter == null) || base.Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data))
     {
         WriteTrace(eventCache, source, eventType, id, null, null, data);
     }
 }
Ejemplo n.º 19
0
		public override void TraceTransfer(TraceEventCache eventCache, string source, int id, string message, Guid relatedActivityId)
		{
			lock(traceRequestMonitor)
			{
				MockTraceListener.transferGuids.Add(relatedActivityId);
			}
		}
Ejemplo n.º 20
0
 public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id)
 {
     var te = new TraceEvent {Cache = eventCache, Source = source, Type = eventType, Id = id};
     Events.Add(te);
     if (OnEventAdd != null)
         OnEventAdd.Invoke(te);
 }
 public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
 {
     ConsoleColor originalColor = Console.ForegroundColor;
     Console.ForegroundColor = GetEventColor(eventType, originalColor);
     base.WriteLine(string.Format(format, args));
     Console.ForegroundColor = originalColor;
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Returns the value of Environment.MachineName
 /// </summary>
 /// <param name="value">The output parameter</param>
 /// <param name="cache">Unused</param>
 /// <param name="source">Unused</param>
 /// <param name="eventType">Unused</param>
 /// <param name="id">Unused</param>
 /// <param name="formatOrMessage">Unused</param>
 /// <param name="data">Unused</param>
 /// <returns>True</returns>
 public override bool TryGetValue(out object value, TraceEventCache cache, string source,
                                  TraceEventType eventType, int id, string formatOrMessage,
                                  object[] data)
 {
     value = Environment.MachineName;
     return true;
 }
        protected override void TraceSimpleEvent(DateTime eventTime, Int32 threadId, TraceEventType eventType, String message, Int32 eventId, TraceEventCache eventCache, String source)
        {
            if (_table != null)
            {
                if (message.StartsWith("#Status ") || message.StartsWith("#Status:"))
                {
                    Status status = new Status(eventTime.ToUniversalTime());
                    status.Level = eventType.ToString();
                    status.ThreadId = threadId;

                    string messageText;
                    string dataText;
                    GetMessageParts(message, out messageText, out dataText);
                    status.Message = messageText;
                    status.Data = dataText;

                    try
                    {
                        TableOperation operation = TableOperation.Insert(status);
                        this._table.Execute(operation);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Exception while saving to Azure storage.");
                        Console.WriteLine(e.ToString());
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Determines whether a filter is attached to this listener and, if so, asks whether it ShouldTrace applies to this data.
 /// </summary>
 protected virtual bool ShouldTrace(TraceEventCache eventCache, string source, TraceEventType eventType, int id,
                                    string formatOrMessage, object[] args, object data1, object[] data)
 {
     return
         !(Filter != null &&
           !Filter.ShouldTrace(eventCache, source, eventType, id, formatOrMessage, args, data1, data));
 }
 public override void TraceTransfer(TraceEventCache eventCache, string source, int id, string message,
     Guid relatedActivityId)
 {
     //this.WriteHeader(source, TraceEventType.Transfer, id, eventCache, relatedActivityId);
     //this.WriteEscaped(message);
     //this.WriteFooter(eventCache);
 }
Ejemplo n.º 26
0
 public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id)
 {
     this.source = source;
     this.eventType = eventType;
     this.id = id;
     TraceEvent(eventCache, source, eventType, id, "No additional information.");
 }
Ejemplo n.º 27
0
		public void WriteEvent(string message, string source, TraceEventType type) {
			var ctx = BeforeWriteEvent();
			try {
				if (source == null) {
					source = s_processFileName;
				}
				var evtId = Interlocked.Increment(ref _evtId);
				var evtCache = new TraceEventCache();
				foreach (TraceListener l in listeners) {
					lock (l) {
						try {
							l.TraceEvent(evtCache, source, type, evtId, message);
							if (Trace.AutoFlush) {
								l.Flush();
							}
						} catch {
							//swallow error
							Debugger.Break();
						}
					}
				}
			} finally {
				AfterWriteEvent(ctx);
			}
		}
 public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id)
 {
     if (_enabled)
     {
         WebSocketHost.Send($"{eventType}:{id} - {source}");
     }
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Traces the message. Supported event types are: Critical, Error, Information and Warning.
        /// </summary>
        public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
        {
            if (Logger != null)
            {
                switch (eventType)
                {
                    case TraceEventType.Critical:
                        {
                            Logger.Fatal(message);
                        }
                        break;

                    case TraceEventType.Error:
                        {
                            Logger.Error(message);
                        }
                        break;

                    case TraceEventType.Information:
                        {
                            Logger.Info(message);
                        }
                        break;

                    case TraceEventType.Warning:
                        {
                            Logger.Warn(message);
                        }
                        break;
                }
            }
        }
        public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
        {
            string message = string.Format(format, args);

            // write the localised date and time but include the time zone in brackets (good for combining logs from different timezones)
            TimeSpan utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
            string plusOrMinus = (utcOffset < TimeSpan.Zero) ? "-" : "+";
            string utcHourOffset = utcOffset.TotalHours == 0 ? string.Empty : string.Format(" ({0}{1:hh})", plusOrMinus, utcOffset);
            string dateWithOffset = string.Format(@"{0:yyyy/MM/dd HH:mm:ss.fff}{1}", DateTime.Now, utcHourOffset);

            // display the threadid
            string log = string.Format(@"{0} [{1}] {2}", dateWithOffset, Thread.CurrentThread.ManagedThreadId, message);

            switch (eventType)
            {
                case TraceEventType.Critical:
                case TraceEventType.Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(log);
                    Console.ResetColor();
                    break;

                case TraceEventType.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine(log);
                    Console.ResetColor();
                    break;

                default:
                    Console.WriteLine(log);
                    break;
            }
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Method invoked when data needs to be traced. Will filter based on current trace options
 /// </summary>
 /// <param name="eventCache">TraceEventCache</param>
 /// <param name="source">Source</param>
 /// <param name="eventType">TraceEventType</param>
 /// <param name="id">ID</param>
 /// <param name="data">Data</param>
 public override void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, object data)
 {
     // If there's no filter means we should log everything
     if (this.Filter == null || this.Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null))
     {
         this.AddNewEntry(data as LogEntry);
     }
 }
        /// <summary>
        /// Writes trace information, a message, and event information to the listener specific output.
        /// </summary>
        /// <param name="eventCache">A <see cref="T:System.Diagnostics.TraceEventCache" /> object that contains the current process ID, thread ID, and stack trace information.</param>
        /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param>
        /// <param name="eventType">One of the <see cref="T:System.Diagnostics.TraceEventType" /> values specifying the type of event that has caused the trace.</param>
        /// <param name="id">A numeric identifier for the event.</param>
        /// <param name="message">A message to write.</param>
        /// <PermissionSet>
        ///   <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
        ///   <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode" />
        ///   </PermissionSet>
        public override void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
        {
            // Check if any filters exist
            if (SourceFilters != null)
            {
                if (SourceFilters.Count > 0)
                {
                    bool isFilterMatched = false;

                    // If there are filters, check to make sure the source matches one of the filters. If it doesn't, then just return.
                    foreach (string filter in SourceFilters)
                    {
                        if (String.Compare(source, filter, true) == 0)
                        {
                            isFilterMatched = true;
                            break;
                        }
                    }

                    if (!isFilterMatched)
                    {
                        return;
                    }
                }
            }

            if (MessageKeywordFilters != null)
            {
                if (MessageKeywordFilters.Count > 0)
                {
                    bool isFilterMatched = false;
                    foreach (string keyword in MessageKeywordFilters)
                    {
                        if (message.Contains(keyword))
                        {
                            isFilterMatched = true;
                            break;
                        }
                    }

                    if (!isFilterMatched)
                    {
                        return;
                    }
                }
            }

            string timestamp = eventCache.DateTime.ToLocalTime().ToString("[MM/dd/yy HH:mm:ss.ffff] ");

            // Prepend timestamp to messages with multiple lines so that addition lines in message
            // lines up to first line after the timestamp
            if (message.Contains(Environment.NewLine))
            {
                message = message.Replace(Environment.NewLine, Environment.NewLine + timestamp);
            }

            Write(timestamp + message);
        }
        private void PurgeLogFiles(int maxFilesToKeep, System.Diagnostics.TraceEventCache eventCache)
        {
            string fileFilter = BaseFileName + "*.log";

            lock (_purgeLock)
            {
                if (DateTime.Now.Date == _lastPurgeDateTime.Date)
                {
                    // only need to perform one purge per day (since this is a daily logger).
                    return;
                }
                else if (Directory.GetFiles(CustomLocation, fileFilter).Length <= maxFilesToKeep)
                {
                    // purge only if more than max number of log files allowed
                    return;
                }
                else if (_purgeTask != null && _purgeTask.Status == TaskStatus.Running)
                {
                    // purge only if no purge task is in progress
                    return;
                }
                else
                {
                    _lastPurgeDateTime = DateTime.Now; // record purge date/time

                    _purgeTask = Task.Factory.StartNew(() =>
                    {
                        var logDir      = CustomLocation;
                        var logFileList = new DirectoryInfo(logDir).GetFiles(fileFilter);
                        var sorted      = logFileList.OrderBy(f => f.LastWriteTime).ToList();
                        while (sorted.Count > maxFilesToKeep)
                        {
                            File.Delete(sorted[0].FullName);
                            sorted.RemoveAt(0);
                        }
                    });
                    // handle exception if any
                    _purgeTask.ContinueWith(t =>
                    {
                        Exception ex = t.Exception;
                        if (ex != null && ex.InnerException != null)
                        {
                            ex = ex.InnerException;
                            // Only want to log purge error once during the life of the run app.
                            // Otherwise, we could potentially log purge error for each log message!
                            if (!_purgeErrLogged)
                            {
                                _purgeErrLogged = true;
                                string message  = "DailyTextWriterListener.PurgeLogFiles(): failed with exception: " + ex.ToString();
                                base.WriteLine(eventCache.DateTime.ToLocalTime().ToString("MM/dd/yy,HH:mm:ss.ffff,") + message);
                            }
                        }
                    });
                } // else
            }     // lock
        }
Ejemplo n.º 34
0
 public virtual void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id)
 {
     TraceEvent(eventCache, source, eventType, id, String.Empty);
 }
Ejemplo n.º 35
0
 public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 36
0
 public override void TraceTransfer(TraceEventCache eventCache, string source, int id, string message, Guid relatedActivityId)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 37
0
 public override void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType severity, int id, string message)
 {
 }
Ejemplo n.º 38
0
 public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 39
0
 private void WriteHeader(String source, TraceEventType eventType, int id, TraceEventCache eventCache)
 {
     WriteStartHeader(source, eventType, id, eventCache);
     WriteEndHeader(eventCache);
 }
 public virtual void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType,
                                int id, string message)
 {
     TraceData(eventCache, source, eventType, id, message);
 }
 public virtual void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object [] args)
 {
     TraceEvent(eventCache, source, eventType, id, String.Format(format, args));
 }
 public virtual void TraceTransfer(TraceEventCache eventCache, string source, int id, string message, Guid relatedActivityId)
 {
     TraceEvent(eventCache, source, TraceEventType.Transfer, id, String.Format("{0}, relatedActivityId={1}", message, relatedActivityId));
 }
        void TraceCore(TraceEventCache eventCache,
                       string source, TraceEventType eventType, int id,
                       bool hasRelatedActivity, Guid relatedActivity,
                       int level, bool wrapData, params object [] data)
        {
            Process p = eventCache != null?
                        Process.GetProcessById(eventCache.ProcessId) :
                            Process.GetCurrentProcess();

            w.WriteStartElement("E2ETraceEvent", e2e_ns);

            // <System>
            w.WriteStartElement("System", sys_ns);
            w.WriteStartElement("EventID", sys_ns);
            w.WriteString(XmlConvert.ToString(id));
            w.WriteEndElement();
            // FIXME: find out what should be written
            w.WriteStartElement("Type", sys_ns);
            w.WriteString("3");
            w.WriteEndElement();
            w.WriteStartElement("SubType", sys_ns);
            // FIXME: it does not seem always to match eventType value ...
            w.WriteAttributeString("Name", eventType.ToString());
            // FIXME: find out what should be written
            w.WriteString("0");
            w.WriteEndElement();
            // FIXME: find out what should be written
            w.WriteStartElement("Level", sys_ns);
            w.WriteString(level.ToString());
            w.WriteEndElement();
            w.WriteStartElement("TimeCreated", sys_ns);
            w.WriteAttributeString("SystemTime", XmlConvert.ToString(eventCache != null ? eventCache.DateTime : DateTime.Now));
            w.WriteEndElement();
            w.WriteStartElement("Source", sys_ns);
            w.WriteAttributeString("Name", source);
            w.WriteEndElement();
            w.WriteStartElement("Correlation", sys_ns);
            w.WriteAttributeString("ActivityID", String.Concat("{", Guid.Empty, "}"));
            w.WriteEndElement();
            w.WriteStartElement("Execution", sys_ns);
            // FIXME: which should I use here?
            //w.WriteAttributeString ("ProcessName", p.ProcessName);
            w.WriteAttributeString("ProcessName", p.MainModule.ModuleName);
            w.WriteAttributeString("ProcessID", p.Id.ToString());
            w.WriteAttributeString("ThreadID", eventCache != null ? eventCache.ThreadId : Thread.CurrentThread.ManagedThreadId.ToString());
            w.WriteEndElement();
            w.WriteStartElement("Channel", sys_ns);
            // FIXME: find out what should be written.
            w.WriteEndElement();
            w.WriteStartElement("Computer");
            w.WriteString(p.MachineName);
            w.WriteEndElement();

            w.WriteEndElement();

            // <ApplicationData>
            w.WriteStartElement("ApplicationData", e2e_ns);
            w.WriteStartElement("TraceData", e2e_ns);
            foreach (object o in data)
            {
                if (wrapData)
                {
                    w.WriteStartElement("DataItem", e2e_ns);
                }
                if (o is XPathNavigator)
                {
                    // the output ignores xmlns difference between the parent (E2ETraceEvent and the content node).
                    // To clone such behavior, I took this approach.
                    w.WriteRaw(XPathNavigatorToString((XPathNavigator)o));
                }
                else if (o != null)
                {
                    w.WriteString(o.ToString());
                }
                if (wrapData)
                {
                    w.WriteEndElement();
                }
            }
            w.WriteEndElement();
            w.WriteEndElement();

            w.WriteEndElement();

            w.Flush(); // for XmlWriter
            Flush();   // for TextWriter
        }
Ejemplo n.º 44
0
        void TraceCore(TraceEventCache eventCache,
                       string source, TraceEventType eventType, int id,
                       bool hasRelatedActivity, Guid relatedActivity,
                       int level, bool wrapData, params object [] data)
        {
            Process p = eventCache != null?
                        Process.GetProcessById(eventCache.ProcessId) :
                            Process.GetCurrentProcess();

            w.WriteStartElement("E2ETraceEvent", e2e_ns);

            // <System>
            w.WriteStartElement("System", sys_ns);
            w.WriteStartElement("EventID", sys_ns);
            w.WriteString(XmlConvert.ToString(id));
            w.WriteEndElement();
            // FIXME: find out what should be written
            w.WriteStartElement("Type", sys_ns);
            w.WriteString("3");
            w.WriteEndElement();
            w.WriteStartElement("SubType", sys_ns);
            // FIXME: it does not seem always to match eventType value ...
            w.WriteAttributeString("Name", eventType.ToString());
            // FIXME: find out what should be written
            w.WriteString("0");
            w.WriteEndElement();
            // FIXME: find out what should be written
            w.WriteStartElement("Level", sys_ns);
            w.WriteString(level.ToString());
            w.WriteEndElement();
            w.WriteStartElement("TimeCreated", sys_ns);
            w.WriteAttributeString("SystemTime", XmlConvert.ToString(eventCache != null ? eventCache.DateTime : DateTime.Now));
            w.WriteEndElement();
            w.WriteStartElement("Source", sys_ns);
            w.WriteAttributeString("Name", source);
            w.WriteEndElement();
            w.WriteStartElement("Correlation", sys_ns);
            w.WriteAttributeString("ActivityID", String.Concat("{", Guid.Empty, "}"));
            w.WriteEndElement();
            w.WriteStartElement("Execution", sys_ns);
            // FIXME: which should I use here?
            //w.WriteAttributeString ("ProcessName", p.ProcessName);
            w.WriteAttributeString("ProcessName", p.MainModule.ModuleName);
            w.WriteAttributeString("ProcessID", p.Id.ToString());
            w.WriteAttributeString("ThreadID", eventCache != null ? eventCache.ThreadId : Thread.CurrentThread.ManagedThreadId.ToString());
            w.WriteEndElement();
            w.WriteStartElement("Channel", sys_ns);
            // FIXME: find out what should be written.
            w.WriteEndElement();
            w.WriteStartElement("Computer");
            w.WriteString(p.MachineName);
            w.WriteEndElement();

            w.WriteEndElement();

            // <ApplicationData>
            w.WriteStartElement("ApplicationData", e2e_ns);
            foreach (object o in data)
            {
                if (wrapData)
                {
                    w.WriteStartElement("TraceData", e2e_ns);
                }
                if (o != null)
                {
                    w.WriteString(o.ToString());
                }
                if (wrapData)
                {
                    w.WriteEndElement();
                }
            }
            w.WriteEndElement();

            w.WriteEndElement();
        }
 public override void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, object data)
 {
 }
 public override bool ShouldTrace(TraceEventCache cache, string source, TraceEventType eventType, int id, string formatOrMessage, Object[] args, Object data1, Object[] data)
 {
     return(default(bool));
 }
Ejemplo n.º 47
0
        private void WriteStartHeader(String source, TraceEventType eventType, int id, TraceEventCache eventCache)
        {
            InternalWrite(fixedHeader);

            InternalWrite("<EventID>");
            InternalWrite(((uint)id).ToString(CultureInfo.InvariantCulture));
            InternalWrite("</EventID>");

            InternalWrite("<Type>3</Type>");

            InternalWrite("<SubType Name=\"");
            InternalWrite(eventType.ToString());
            InternalWrite("\">0</SubType>");

            InternalWrite("<Level>");
            int sev = (int)eventType;

            if (sev > 255)
            {
                sev = 255;
            }
            if (sev < 0)
            {
                sev = 0;
            }
            InternalWrite(sev.ToString(CultureInfo.InvariantCulture));
            InternalWrite("</Level>");

            InternalWrite("<TimeCreated SystemTime=\"");
            if (eventCache != null)
            {
                InternalWrite(eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture));
            }
            else
            {
                InternalWrite(DateTime.Now.ToString("o", CultureInfo.InvariantCulture));
            }
            InternalWrite("\" />");

            InternalWrite("<Source Name=\"");
            WriteEscaped(source);
            InternalWrite("\" />");

            InternalWrite("<Correlation ActivityID=\"");
            if (eventCache != null)
            {
                InternalWrite(eventCache.ActivityId.ToString("B"));
            }
            else
            {
                InternalWrite(Guid.Empty.ToString("B"));
            }
        }
 public virtual void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id)
 {
     TraceEvent(eventCache, source, eventType, id, null);
 }
        /// <summary>
        /// Writes trace information, a message and event information to the output file or stream.
        /// </summary>
        /// <param name="eventCache">A <see cref="T:System.Diagnostics.TraceEventCache" /> object that contains the current process ID, thread ID, and stack trace information.</param>
        /// <param name="source">A name of the trace source that invoked this method.</param>
        /// <param name="eventType">One of the <see cref="T:System.Diagnostics.TraceEventType" /> enumeration values.</param>
        /// <param name="id">A numeric identifier for the event.</param>
        /// <param name="message">A message to write.</param>
        /// <PermissionSet>
        ///   <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
        ///   <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
        ///   <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode" />
        ///   </PermissionSet>
        public override void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
        {
            if (!eventType.Equals(TraceEventType.Critical))
            {
                char eventTypeChar = 'E';

                switch (eventType)
                {
                case TraceEventType.Information:
                    eventTypeChar = 'I';
                    break;

                case TraceEventType.Warning:
                    eventTypeChar = 'W';
                    break;

                case TraceEventType.Error:
                    eventTypeChar = 'E';
                    break;

                case TraceEventType.Critical:
                    eventTypeChar = 'C';
                    break;
                }

                string header = String.Format("{0},{1},{2},", eventCache.DateTime.ToLocalTime().ToString("MM/dd/yy,HH:mm:ss.ffff"), id, eventTypeChar);

                // Prepend timestamp to messages with multiple lines so that addition lines in message
                // lines up to first line after the timestamp
                if (message.Contains(Environment.NewLine))
                {
                    message = message.Replace(Environment.NewLine, Environment.NewLine + header);
                }
                BaseFileName = OriginalFileName + "_H" + DateTime.Now.Hour;
                base.WriteLine(header + message);

                PurgeLogFiles(MaxLogFilesAllowed, eventCache); // purge older log files if got to many
            }
            else
            {
                // Maintenance log file header..
                string _date = DateTime.Now.ToString("-yyyy-MM-dd");
                string LogFilePathForMaintenance = string.Format("{0}\\{1}_Maintenance{2}.log", CustomLocation, OriginalFileName, _date);
                if (!File.Exists(LogFilePathForMaintenance))
                {
                    //   File.Create(LogFilePathForMaintenance).Dispose();

                    using (StreamWriter w = File.AppendText(LogFilePathForMaintenance))
                    {
                        w.WriteLine("Time Stamp, Error Code, Error Category, Error Message, Type");
                        w.Close();
                    }
                }
                BaseFileName = OriginalFileName + "_Maintenance";

                string header = String.Format("{0},", eventCache.DateTime.ToLocalTime().ToString("MM/dd/yy - HH:mm:ss"));

                // Prepend timestamp to messages with multiple lines so that addition lines in message
                // lines up to first line after the timestamp
                if (message.Contains(Environment.NewLine))
                {
                    message = message.Replace(Environment.NewLine, Environment.NewLine + header);
                }

                //Force to be not over 5 comma index
                var msgsplit = message.Split(',');
                if (msgsplit.Length > 4)
                {
                    message = string.Empty;
                    message = string.Format("{0},{1},{2},{3}", msgsplit[0], msgsplit[1], msgsplit[2], msgsplit[3]);
                }

                base.WriteLine(header + message);
            }
        }
Ejemplo n.º 50
0
 public override bool ShouldTrace(TraceEventCache cache, string source, TraceEventType eventType, int id, string formatOrMessage,
                                  object[] args, object data1, object[] data)
 {
     return(((int)eventType & (int)level) != 0);
 }
Ejemplo n.º 51
0
 public override bool ShouldTrace(System.Diagnostics.TraceEventCache cache, string source, System.Diagnostics.TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data)
 {
     throw null;
 }
Ejemplo n.º 52
0
 public virtual void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, string format, params object[] args)
 {
 }
Ejemplo n.º 53
0
 public override void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType severity, int id, params object[] data)
 {
 }
Ejemplo n.º 54
0
 public virtual void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, string message)
 {
 }
Ejemplo n.º 55
0
 public override void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType severity, int id, string format, params object[] args)
 {
 }
Ejemplo n.º 56
0
 public virtual void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, params object[] data)
 {
 }
Ejemplo n.º 57
0
 public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 58
0
 public abstract bool ShouldTrace(System.Diagnostics.TraceEventCache cache, string source, System.Diagnostics.TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data);
Ejemplo n.º 59
0
 public virtual void TraceTransfer(TraceEventCache eventCache, string source, int id, string message, Guid relatedActivityId)
 {
     TraceEvent(eventCache, source, TraceEventType.Transfer, id, message + ", relatedActivityId=" + relatedActivityId.ToString());
 }
Ejemplo n.º 60
0
        public static void TraceEvent(TraceEventType eventType, int id, string?format, params object?[]?args)
        {
            TraceEventCache EventCache = new TraceEventCache();

            if (UseGlobalLock)
            {
                lock (critSec)
                {
                    if (args == null)
                    {
                        foreach (TraceListener listener in Listeners)
                        {
                            listener.TraceEvent(EventCache, AppName, eventType, id, format);
                            if (AutoFlush)
                            {
                                listener.Flush();
                            }
                        }
                    }
                    else
                    {
                        foreach (TraceListener listener in Listeners)
                        {
                            listener.TraceEvent(EventCache, AppName, eventType, id, format !, args);
                            if (AutoFlush)
                            {
                                listener.Flush();
                            }
                        }
                    }
                }
            }
            else
            {
                if (args == null)
                {
                    foreach (TraceListener listener in Listeners)
                    {
                        if (!listener.IsThreadSafe)
                        {
                            lock (listener)
                            {
                                listener.TraceEvent(EventCache, AppName, eventType, id, format);
                                if (AutoFlush)
                                {
                                    listener.Flush();
                                }
                            }
                        }
                        else
                        {
                            listener.TraceEvent(EventCache, AppName, eventType, id, format);
                            if (AutoFlush)
                            {
                                listener.Flush();
                            }
                        }
                    }
                }
                else
                {
                    foreach (TraceListener listener in Listeners)
                    {
                        if (!listener.IsThreadSafe)
                        {
                            lock (listener)
                            {
                                listener.TraceEvent(EventCache, AppName, eventType, id, format !, args);
                                if (AutoFlush)
                                {
                                    listener.Flush();
                                }
                            }
                        }
                        else
                        {
                            listener.TraceEvent(EventCache, AppName, eventType, id, format !, args);
                            if (AutoFlush)
                            {
                                listener.Flush();
                            }
                        }
                    }
                }
            }
        }