public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { try { if (!this.ShouldLogTrace(eventType)) { return; } if (eventType == TraceEventType.Critical || eventType == TraceEventType.Error || eventType == TraceEventType.Warning) { WriteTrace(eventType.ToString(), string.Format(format, args), eventCache.Callstack.ToString(), eventCache.ThreadId, source, "", 0, "", "", "", 0, eventCache.DateTime); } else { WriteTrace(eventType.ToString(), string.Format(format, args), "", eventCache.ThreadId, source, "", 0, "", "", "", 0, eventCache.DateTime); } } catch (Exception ex) { this.WriteLine( string.Format("AND::DbTraceListener - Trace.TraceTransfer failed with following exception: {0}, for message {1} ", ex.ToString(), string.Format(format, args)), "Error", "DBTraceListener" ); this.WriteEntryToInternalLog(string.Format("Trace.TraceTransfer failed with following exception: {0}", ex.ToString())); } }
#pragma warning restore 56500 protected static string LookupSeverity(TraceEventType type) { string s; switch (type) { case TraceEventType.Critical: s = "Critical"; break; case TraceEventType.Error: s = "Error"; break; case TraceEventType.Warning: s = "Warning"; break; case TraceEventType.Information: s = "Information"; break; case TraceEventType.Verbose: s = "Verbose"; break; case TraceEventType.Start: s = "Start"; break; case TraceEventType.Stop: s = "Stop"; break; case TraceEventType.Suspend: s = "Suspend"; break; case TraceEventType.Transfer: s = "Transfer"; break; default: s = type.ToString(); break; } #pragma warning disable 618 Fx.Assert(s == type.ToString(), "Return value should equal the name of the enum"); #pragma warning restore 618 return(s); }
// ReSharper restore MethodOverloadWithOptionalParameter // ReSharper disable MethodOverloadWithOptionalParameter public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { // ReSharper disable ConditionIsAlwaysTrueOrFalse if (args == null) // ReSharper restore ConditionIsAlwaysTrueOrFalse // ReSharper disable HeuristicUnreachableCode { _traceLog.Clients.All.traceEvent(source, eventType.ToString(), id, format, args); } // ReSharper restore HeuristicUnreachableCode else { _traceLog.Clients.All.traceEvent(source, eventType.ToString(), id, string.Format(CultureInfo.InvariantCulture, format, args)); } }
public static void Log(TraceEventType eventType, int id, string message, bool toExit, bool msgPrint) { string messageFormated = string.Format(_messageFormat, eventType.ToString(), CurrentDateTime(), message); //verbose log if (_verboseLog) { // write diagnostics _ts.TraceEvent(eventType, id, "\n" + message); _ts.Flush(); // write general logs using (StreamWriter sw = File.AppendText(_generalLogPath)) { sw.WriteLine(messageFormated); } } // write console logs if (msgPrint) { //Console.WriteLine("*** {0} - [id:{1}]: {2}", eventType.ToString(), id.ToString(), message); Console.WriteLine(messageFormated); } // exit condition if (toExit) { Console.ReadKey(); System.Environment.Exit(1); return; } }
internal static void TraceEvent(TraceEventType type, string code, string description, TraceRecord trace, Exception exception, ref Guid activityId, bool emitTransfer, object source) { if (ShouldTrace(type)) { using (Activity.CreateActivity(activityId, emitTransfer)) { XPathNavigator navigator = BuildTraceString(type, code, description, trace, exception, source); try { TraceSource.TraceData(type, 0, navigator); if (s_calledShutdown) { TraceSource.Flush(); } } catch (OutOfMemoryException) { throw; } catch (Exception e) { string traceString = SR.Format(SR.TraceFailure, type.ToString(), code, description, source == null ? string.Empty : CreateSourceString(source)); LogTraceFailure(traceString, e); } } } }
public static void Log(string sMessage, TraceEventType tet, LogLevel level) { if (level > currentLogLevel || currentLogLevel == LogLevel.Silent) { return; } if (twLog == null) { try { CreateLogFile(); } catch (Exception e) { Console.WriteLine(String.Format("Exception from CreateLogFile(): {0}", e.Message)); Console.WriteLine(String.Format( "Failed to create log file in {0}. Continuing with logging disabled.", Configurations.tempDirectory == null ? "<null>" : Configurations.tempDirectory)); currentLogLevel = LogLevel.Silent; return; } if (currentLogLevel == LogLevel.Silent) { return; } } string logString = String.Format("{0}{1}{2}", (use_timestamp ? DateTime.Now.ToString("[yyyy-MM-dd hh:mm:ss,fff] ") : ""), (use_tag ? (" [" + tet.ToString() + "] ") : ""), sMessage); twLog.WriteLine(logString); twLog.Flush(); }
private void WriteHeaderDetail(String source, TraceEventType eventType, int id, TraceEventCache eventCache, TraceLog log) { var sev = (int)eventType; if (sev > 255) { sev = 255; } if (sev < 0) { sev = 0; } log.Component = componentName; log.Host = GetHostHeader(); log.UrlLocalPath = GetRequestLocalPath(); log.EventId = ((uint)id); log.Type = eventType.ToString(); log.Severity = sev; log.TimeCreated = DateTime.UtcNow; log.TimeCreatedFormatted = DateTime.UtcNow.ToString("o"); log.LocalTimeCreated = DateTime.Now; log.LocalTimeCreatedFormatted = DateTime.Now.ToString("o"); log.SourceName = source; log.CorrelationActivityId = eventCache != null?System.Diagnostics.Trace.CorrelationManager.ActivityId.ToString() : Guid.Empty.ToString("B"); log.MachineName = machineName; log.RequestId = GetRequestId(); log.Environment = GetEnvironment(); WriteFooter(eventCache, log); }
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { string value = message; try { using (System.IO.StringReader sr = new System.IO.StringReader(message)) using (System.Xml.XmlReader xr = System.Xml.XmlReader.Create(sr)) { while (xr.Read()) { if (eventType == TraceEventType.Critical) { if (xr.NodeType == System.Xml.XmlNodeType.Element && xr.Name == "Message") { value = xr.ReadString(); break; } } else { if (xr.NodeType == System.Xml.XmlNodeType.Element && xr.Name == "Value") { value = xr.ReadString(); break; } } } } } catch (Exception) { } Trace.WriteLine(source + ": " + value + " (" + eventType.ToString() + ")"); }
private string AddHeader(string source, TraceEventType eventType, int id) { string eventTypeName = eventType.ToString(); switch (eventType) { case TraceEventType.Critical: eventTypeName = "^7" + eventTypeName + ":^0"; break; case TraceEventType.Error: eventTypeName = "^8" + eventTypeName + ":^0"; break; case TraceEventType.Warning: eventTypeName = "^3" + eventTypeName + ":^0"; break; case TraceEventType.Information: eventTypeName = "^4" + eventTypeName + ":^0"; break; case TraceEventType.Verbose: eventTypeName = "^2" + eventTypeName + ":^0"; break; default: eventTypeName = "^0" + eventTypeName + ":^0"; break; } return string.Format(CultureInfo.InvariantCulture, "{0}{1} ", new object[] { string.IsNullOrEmpty(source) ? string.Empty : string.Format("[{0}] ",source), eventTypeName, }); }
public void Write(object message, ICollection <string> categories, int priority, int eventId, TraceEventType severity, string title, IDictionary <string, object> properties) { var props = Utility.CollectAutoProperties(properties); var eventTypeName = severity.ToString().ToUpper(); if (SnTrace.Event.Enabled) { if (severity <= TraceEventType.Information) // Critical = 1, Error = 2, Warning = 4, Information = 8 { var id = "#" + Guid.NewGuid().ToString(); props["SnTrace"] = id; SnTrace.Event.Write("{0} {1}: {2}", eventTypeName, id, message); } else { object id = "-"; object path = "-"; if (properties != null) { properties.TryGetValue("Id", out id); properties.TryGetValue("Path", out path); } if (categories.Count == 1 && categories.First() == "Audit") { eventTypeName = "Audit"; } SnTrace.Event.Write("{0}: {1}, Id:{2}, Path:{3}", eventTypeName, message, id, path); } } Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write( message ?? String.Empty, categories ?? null, priority, eventId, severity, title ?? string.Empty, props); }
/// <summary> /// Executes the WriteLog stored procedure. /// </summary> /// <param name="eventId">The event id for this LogEntry.</param> /// <param name="priority">The priority for this LogEntry.</param> /// <param name="severity">The severity for this LogEntry.</param> /// <param name="title">The title for this LogEntry.</param> /// <param name="timeStamp">The timestamp for this LogEntry.</param> /// <param name="machineName">The machine name for this LogEntry.</param> /// <param name="appDomainName">The appDomainName for this LogEntry.</param> /// <param name="processId">The process id for this LogEntry.</param> /// <param name="processName">The processName for this LogEntry.</param> /// <param name="managedThreadName">The managedthreadName for this LogEntry.</param> /// <param name="win32ThreadId">The win32threadID for this LogEntry.</param> /// <param name="message">The message for this LogEntry.</param> private void WriteLog( int eventId, int priority, TraceEventType severity, string title, DateTime timeStamp, string machineName, string appDomainName, string processId, string processName, string managedThreadName, string win32ThreadId, string message) { var appLogEntry = new ApplicationLog() { EventId = eventId, Priority = priority, Severity = severity.ToString(), Title = title, Timestamp = timeStamp, MachineName = machineName, AppDomainName = appDomainName, ProcessId = processId, ProcessName = processName, ThreadName = managedThreadName, Win32ThreadId = win32ThreadId, Message = message, FormattedMessage = message, }; DataServiceProvider.DataService.UpdateObject(appLogEntry); }
private void HandleEvent(TraceEventType eventType, params object[] data) { if (data.Length == 1) { Write("[" + eventType.ToString()[0] + "] " + data[0]); } }
// ////////////////////////////////////////////////////////// // Public Methods /// <summary> /// Gets the console color set for the specified event type, or the default color. /// </summary> /// <param name="eventType">TraceEventType to get the ConsoleColor for.</param> /// <returns>The ConsoleColor used to display the specified TraceEventType.</returns> public ConsoleColor GetConsoleColor(TraceEventType eventType) { var key = eventType.ToString() + "Color"; if (Attributes.ContainsKey(key)) { var setting = Attributes[key]; if (Enum.IsDefined(typeof(ConsoleColor), setting)) { return((ConsoleColor)Enum.Parse(typeof(ConsoleColor), setting)); } } if (((int)eventType & (int)SourceLevels.ActivityTracing) > 0 && Attributes.ContainsKey("activityTracingColor")) { var setting = Attributes["activityTracingColor"]; if (Enum.IsDefined(typeof(ConsoleColor), setting)) { return((ConsoleColor)Enum.Parse(typeof(ConsoleColor), setting)); } } return(GetDefaultColor(eventType)); }
public void WriteLogMessage(string message, TraceEventType eventType) { switch (eventType) { case TraceEventType.Critical: case TraceEventType.Error: Error(message); break; case TraceEventType.Warning: Warning(message); break; case TraceEventType.Information: Info(message); break; case TraceEventType.Verbose: Verbose(message); break; default: Verbose($"{eventType.ToString()} - {message}"); break; } }
/// <summary> /// Trace /// </summary> /// <param name="workflowOid">Workflow Oid</param> /// <param name="action">Action</param> /// <param name="code">Code</param> /// <param name="result">Result</param> /// <param name="user">User</param> /// <param name="msg">Msg</param> /// <param name="type">Type</param> public void Trace(Guid workflowOid, ActionTrace action, string code, string result, string user, string msg, TraceEventType type) { using (var uofw = new FlowTasksUnitOfWork()) { var wfd = uofw.WorkflowDefinitions.First(w => w.WorkflowOid == workflowOid); var eventType = type.ToString(); var tre = uofw.TraceEvents.First(e => e.Type == eventType); var t = new WorkflowTrace { Message = msg.Substring(0, Math.Min(msg.Length, 500)), TraceEvent = tre, User = string.IsNullOrWhiteSpace(user) ? string.Empty : user, When = DateTime.Now, WorkflowDefinition = wfd, Action = action.ToString(), Code = code, Result = result }; uofw.WorkflowTraces.Insert(t); uofw.Commit(); } }
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { if ((Filter != null) && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null)) return; var message = data.ToString(); WriteLine(message, eventType.ToString()); }
private static string LookupSeverity(TraceEventType type) { switch (type) { case TraceEventType.Critical: return("Critical"); case TraceEventType.Error: return("Error"); case TraceEventType.Warning: return("Warning"); case TraceEventType.Information: return("Information"); case TraceEventType.Verbose: return("Verbose"); case TraceEventType.Suspend: return("Suspend"); case TraceEventType.Transfer: return("Transfer"); case TraceEventType.Start: return("Start"); case TraceEventType.Stop: return("Stop"); } return(type.ToString()); }
private void WriteTraceEvent(string source, TraceEventType eventType, int eventId, string message) { if (string.IsNullOrEmpty(source)) { source = "(event)"; } DateTime time = DateTime.Now; ListViewItem item = new ListViewItem(); item.Text = message; item.SubItems.Add(time.ToString("g")); item.SubItems.Add(source); item.SubItems.Add(eventType.ToString()); item.SubItems.Add(eventId.ToString()); _probeEvents.AddEvent(source, time, eventType, message, eventId); _probeEventList.Invoke(new UniversalVoidDelegate(() => _probeEventList.Items.Add(item))); if (eventType < TraceEventType.Information) { Invoke(new UniversalVoidDelegate(() => { if (_trayIcon.Visible && _trayIcon.Icon != Properties.Resources.redEye) { _trayIcon.Icon = Properties.Resources.redEye; _trayIcon.ShowBalloonTip(3, source, string.Format("{0} - {1}", source, message), ToolTipIcon.Info); } })); } }
/// <summary> /// Writes a trace event message to the trace listeners in the Listeners collection using the specified event type and event identifier. /// </summary> /// <param name="traceSource">The 'TraceSource' instance.</param> /// <param name="traceEventType">One of the enumeration values that specifies the event type of the trace data.</param> /// <param name="message">The informative message to write.</param> /// <param name="duration">The trace event duration.</param> /// <param name="status">One of the enumeration values that specifies the event status of the trace event.</param> /// <param name="exception">THe exception that to trace as part of the trace event.</param> /// <param name="data">The trace data.</param> /// <param name="methodName">The calling method where the log originated from</param> internal static void TraceEventInternal(this TraceSource traceSource, TraceEventType traceEventType, string message, TimeSpan duration, TraceStatus status, Exception exception, IEnumerable <KeyValuePair <string, object> > data, string methodName) { try { if (!TraceSourceExt.ShouldTrace(traceSource, traceEventType)) { return; } TraceEventEntry traceEventEntry = TraceEventEntryBuilder.IncludeEnvironmentData(new TraceEventEntry() { ApplicationName = traceSource.Name, EventData = TraceSourceExt.EventDataBuilder.CreateTraceEventData(exception, data), EventDuration = duration, EventKeys = TraceSourceExt.EventDataBuilder.CreateEventKeys(TraceSourceExt.GetKeys()), EventType = traceEventType.ToString(), Message = message, MethodName = methodName, Status = (int)status }); traceSource.TraceData(traceEventType, 0, (object)traceEventEntry); traceSource.Flush(); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(string.Format("An error occurred while tracing. {0}", (object)ex.Message)); } }
private void WriteLine(string message, TraceEventType eventType) { if ((this.Filter == null) || this.Filter.ShouldTrace(null, null, eventType, 0, null, null, null, null)) { this.WriteLine(message, eventType.ToString()); } }
// Altered from the original .Net Core implementation. private void WriteHeader(string source, TraceEventType eventType, int id) { string type = null; switch (eventType) { case TraceEventType.Critical: type = "CRIT"; break; case TraceEventType.Error: type = "ERR "; break; case TraceEventType.Warning: type = "WARN"; break; case TraceEventType.Information: type = "INFO"; break; case TraceEventType.Verbose: type = "VERB"; break; default: type = eventType.ToString(); break; } Write(StringUtil.Format("[{0:u} {1} {2}] ", DateTime.UtcNow, type, source)); }
KeyValuePair <string, string> BuildEmailMessage(string source, TraceEventType eventType, int id, string message) { string subject = ""; if (String.IsNullOrEmpty(EmailFormatSubject)) { subject += eventType.ToString(); subject += " - "; subject += source; subject += " - "; subject += id.ToString(); } else { subject = BuildFormatString(EmailFormatSubject, message); } string body = message; if (!String.IsNullOrEmpty(EmailFormatBody)) { body = BuildFormatString(EmailFormatBody, message); } return(new KeyValuePair <string, string>(subject, body)); }
/// <summary> /// String serialization of <see cref="TraceEventData" />. /// </summary> /// <returns>A string representing the <see cref="TraceEventData" /> instace.</returns> /// <remarks> /// To help visualization in basic TraceListener like the DefaultTraceListener (Visual Studio, DebugViewer). /// </remarks> public override string ToString() { if (TraceCategory == TraceCategory.Performance) { return(string.Format(CultureInfo.CurrentCulture, "{0}-{1}|{2}-{3}|{4}|{5}|{6}|{7}ms", TraceSourceType.ToString(), TraceSourceName, TraceEventType.ToString(), TraceEventName, TraceCategory, CreationDate, Message, ElapsedTime)); } if (TraceCategory == TraceCategory.Error || TraceCategory == TraceCategory.Warning && RawException != null) { return(string.Format(CultureInfo.CurrentCulture, "{0}-{1}|{2}-{3}|{4}|{5}|{6}|{7}|{8}|{9}", TraceSourceType.ToString(), TraceSourceName, TraceEventType.ToString(), TraceEventName, TraceCategory, CreationDate, Message, ExceptionType, RawException, StackTrace)); } return(string.Format(CultureInfo.CurrentCulture, "{0}-{1}|{2}-{3}|{4}|{5}|{6}", TraceSourceType.ToString(), TraceSourceName, TraceEventType.ToString(), TraceEventName, TraceCategory, CreationDate, Message)); }
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { var levelChar = eventType.ToString().Substring(0, 1).ToUpper(); var dateFormat = DateTime.Now.ToString("0:MM/dd/yy H:mm:ss"); string fmt = string.Format("{0} {1} {2} ({3})", DateTime.Now.ToString(), levelChar, message, source); this.WriteLine(fmt); }
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; } } } }
// ReSharper disable MethodOverloadWithOptionalParameter public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) // ReSharper restore MethodOverloadWithOptionalParameter { // ReSharper disable ConditionIsAlwaysTrueOrFalse if (args == null) // ReSharper restore ConditionIsAlwaysTrueOrFalse // ReSharper disable HeuristicUnreachableCode { _traceLog.Clients.All.traceEvent(source, eventType.ToString(), id, format, args); } // ReSharper restore HeuristicUnreachableCode else { _traceLog.Clients.All.traceEvent(source, eventType.ToString(), id, string.Format(CultureInfo.InvariantCulture, format, args)); } }
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { if (eventType == TraceEventType.Information) { WriteLine(String.Format("{0:HH:mm:ss.ffff} - {1}", eventCache.DateTime.ToLocalTime(), message)); } else { WriteLine(String.Format("{0:HH:mm:ss.ffff} - {1}: {2}", eventCache.DateTime.ToLocalTime(), eventType.ToString().ToUpper(), message)); } }
private TraceEvent CreateEvent(TraceEventType type, string desc) { return(new TraceEvent { Type = type.ToString(), Description = desc }); }
public void Trace(TraceEventType type, int id, params object[] message) { var formattedMessage = message.Select(x => x.ToString()).Aggregate((c, n) => c + "," + n); var msg = $"{type.ToString().ToUpper()}({id}): {formattedMessage}"; Logs.Add(msg); Debug.WriteLine(msg); }
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { sender.Send( id: id.ToString(), severity: eventType.ToString(), data: data ); }
private void WriteHeader(string source, TraceEventType eventType, int id) { this.WriteEscaped(source); this.Write(this.Delimiter); this.Write(eventType.ToString()); this.Write(this.Delimiter); this.Write(id.ToString(CultureInfo.InvariantCulture)); this.Write(this.Delimiter); }
/// <summary> /// After determining if tracing should be performed according to the configured <see cref="TraceListener.Filter"/>, /// issues the <see cref="WriteLine"/> call. /// </summary> /// <param name="eventCache">The event cache that contains extra information about the trace context.</param> /// <param name="source">The trace source name that issued the trace.</param> /// <param name="eventType">Type of the event.</param> /// <param name="message">The message to trace.</param> /// <remarks> /// <see cref="TraceEventType.Resume"/>, <see cref="TraceEventType.Stop"/>, /// <see cref="TraceEventType.Resume"/> and <see cref="TraceEventType.Transfer"/> traces are ignored. /// </remarks> protected virtual void DoTrace(TraceEventCache eventCache, string source, TraceEventType eventType, string message) { if (ignoredEvents.Contains(eventType)) { return; } WriteLine(eventType.ToString().PadRight(MaxEventTypeLength) + ": " + message); }
protected string MessageWithTraceEventType(TraceEventType traceEventType, string message) { string traceEventTypeString; if (!TraceEventTypeStrings.TryGetValue(traceEventType, out traceEventTypeString)) { traceEventTypeString = traceEventType.ToString(); } return string.Format(CultureInfo.InvariantCulture, MessageWithTraceEventTypeFormat, traceEventTypeString, message); }
/// <summary> /// Writes a message to the log using the specified /// category. /// </summary> /// <param name="message"></param> /// <param name="category"></param> private static void Write(string message, TraceEventType severity) { LogEntry entry = new LogEntry(); entry.Categories.Add(severity.ToString()); entry.Message = message; entry.Severity = severity; writer.Write(entry); }
private static void AppendHeader(this StringBuilder builder, string source, TraceEventType eventType, int id, string delimiter = DefaultDelimiter) { builder.Append(EscapedString(source)); builder.Append(delimiter); builder.Append(eventType.ToString()); builder.Append(delimiter); builder.Append(id.ToString(CultureInfo.InvariantCulture)); builder.Append(delimiter); }
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { if (eventType == TraceEventType.Critical || eventType == TraceEventType.Error) { Errors.Add(message); } AppendLine(message, eventType.ToString()); }
public void TestTraceListenerThrowsOnErrorOrWarning(TraceEventType traceEventType) { // Given Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); engine.Pipelines.Add(new Trace(traceEventType.ToString()).EventType(traceEventType)); // When/Then Assert.Throws<Exception>(() => engine.Execute()); }
public void TestTraceListenerThrows(TraceEventType traceEventType) { // Given Engine engine = new Engine(); engine.Pipelines.Add(new Trace(traceEventType.ToString()).EventType(traceEventType)); // When TestDelegate test = () => engine.Execute(); // Then Assert.Throws<Exception>(test); }
private void SendCampfireMessage(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data) { // iterate through the data and create a single message StringBuilder sb = new StringBuilder(); foreach (object item in data.Where(item => item != null)) sb.Append(item); // Source LogLevel (id): message string message = string.Format("{0} {1} ({2}): {3}", source, eventType.ToString(), id, sb.ToString()); _client.Post(message); }
public void Write( TraceEventType eventType, string message ) { StreamWriter writer = File.AppendText( filename ); try { writer.WriteLine( "[{0:yyyy-MM-dd HH:mm:ss.fff}] {1}: {2}", DateTime.Now, eventType.ToString(), message ); } finally { writer.Close(); } }
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)) return; StackTrace stackTrace = new StackTrace(true); StackFrame[] stackFrames = stackTrace.GetFrames(); this.Writer.WriteLine("<entry date='" + Gateway.Now.ToShortDateString() + "' time='" + Gateway.Now.ToShortTimeString() + "' type='" + eventType.ToString() + "' chainId='" + id + "'>" + "<sender class='" + stackFrames[3].GetMethod().ReflectedType.Name + "." + stackFrames[3].GetMethod().Name + "' line='" + stackFrames[3].GetFileLineNumber() + "' />" + "<message>" + message + "</message></entry>"); }
public void Log(TraceEventType type, Exception ex, IDictionary<string, object> additionalInfo, string messageFormat, params object[] args) { string messageText = args == null || args.Length == 0 ? messageFormat : String.Format(messageFormat, args); string spiedMessage = String.Format("[{0}] {1}", type.ToString().ToUpperInvariant(), messageText); for (; ex != null; ex = ex.InnerException) spiedMessage += String.Format("\r\nEXCEPTION:\r\n{0}", ex); if (additionalInfo != null && additionalInfo.Count != 0) spiedMessage += String.Format("\r\nADDITIONAL INFO: {0}", String.Join(", ", additionalInfo.Select(kvp => String.Format("{0} = {1}", kvp.Key, kvp.Value)))); Messages.Add(spiedMessage); }
private static void WriteEvent(TraceEventType eventType, CompositionTraceId traceId, string format, params object[] arguments) { const string LEVEL = "Level = "; const string ID = " ,Id = "; const string NEW_LINE = "\r\n"; StringBuilder sb = new StringBuilder (60); sb.Append (LEVEL); sb.Append (eventType); sb.Append (ID); sb.Append (traceId); sb.Append (NEW_LINE); sb.AppendFormat (format, arguments); var mssage = eventType.ToString() + string.Format(format, arguments); }
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data) { if ((Filter != null) && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null)) return; var stringBuilder = new StringBuilder(); for (var i = 0; i < data.Length; i++) { if (i != 0) { stringBuilder.Append(", "); } if (data[i] != null) { stringBuilder.Append(data[i]); } } WriteLine(stringBuilder.ToString(), eventType.ToString()); }
internal static string CreateLogMessage(TraceEventType eventType, CompositionTraceId traceId, string format, params object[] arguments) { StringBuilder messageBuilder = new StringBuilder(); // Format taken from TraceListener.TraceEvent in full framework messageBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0} {1}: {2} : ", s_sourceName, eventType.ToString(), (int)traceId); if (arguments == null) { messageBuilder.Append(format); } else { messageBuilder.AppendFormat(CultureInfo.InvariantCulture, format, arguments); } messageBuilder.AppendLine(); return messageBuilder.ToString(); }
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { var localData = data.ToString(); // Try and match data to a TraceRecord and so we an write better output. ToString() on data is putting the running app info on. // possible future enhancement of breaking it back to trace record and writing more discrete fields try { var navigator = data as XPathNavigator; if (navigator != null) { var xElement = navigator.UnderlyingObject as XElement; if (xElement != null) { var singleOrDefault = xElement.Elements().SingleOrDefault(a => a.Name.LocalName == "Description"); if (singleOrDefault != null) { localData = singleOrDefault.Value; } } } } catch (Exception) { //reset localData = data.ToString(); } var storage = new Storage(StorageHelper.GetSessionStorageKey()); // Store the info in http runtime cache storage.Write(new LocalizationMessage { Name = source, EventType = eventType.ToString(), Id = id, Data = localData }); }
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; string idDescription; if (source == "ExcelDna.Integration") { // For this source, we interpret the event id as a grouping IntegrationTraceEventId traceEventId = (IntegrationTraceEventId)id; idDescription = traceEventId.ToString(); } else { idDescription = id.ToString(CultureInfo.InvariantCulture); } string header = string.Format(CultureInfo.InvariantCulture, "{0} [{1}] ", idDescription, eventType.ToString()); base.TraceEvent(eventCache, source, eventType, id, header + format, args); if (eventType == TraceEventType.Error || eventType == TraceEventType.Critical) LogDisplay.Show(); }
void Log(TraceEventType eventType, string message, params object[] args) { if (TraceLogger.IntegrationTraceSource == null) { // We are in the pre-initialization stage. Just log to Debug. // NOTE: Without the explcit check and short-circuit here the loading would (sometimes!) fail. // This is despite the catch-all exception handler that should be suppressing all errors. // Somehow the null-reference exception being thrown and caught interferes with the AppDomain_AssemblyResolve!? // The problem only happened when ExcelDna.Integration had to be resolved from resources (in which case the calls here would come from AssemblyResolve. // Under the debugger, the problem was inconsistent (sometimes the load worked fine), but outside the debugger it always failed. Debug.Print(eventType.ToString() + " : " + string.Format(message, args)); return; } try { TraceLogger.IntegrationTraceSource.TraceEvent(eventType, _eventId, message, args); } catch (Exception e) { // We certainly want to suppress errors here, though they indicate Excel-DNA bugs. Debug.Print("ExcelDna.Loader - Logger.Log error: " + e.Message); } }
#pragma warning restore 56500 protected static string LookupSeverity(TraceEventType type) { string s; switch (type) { case TraceEventType.Critical: s = "Critical"; break; case TraceEventType.Error: s = "Error"; break; case TraceEventType.Warning: s = "Warning"; break; case TraceEventType.Information: s = "Information"; break; case TraceEventType.Verbose: s = "Verbose"; break; case TraceEventType.Start: s = "Start"; break; case TraceEventType.Stop: s = "Stop"; break; case TraceEventType.Suspend: s = "Suspend"; break; case TraceEventType.Transfer: s = "Transfer"; break; default: s = type.ToString(); break; } #pragma warning disable 618 Fx.Assert(s == type.ToString(), "Return value should equal the name of the enum"); #pragma warning restore 618 return s; }
/// <summary> /// Logs the specified MSG. /// </summary> /// <param name="msg">The MSG.</param> /// <param name="type">The type.</param> /// <param name="correlationId">The correlation id.</param> //public static void Log(string msg, TraceEventType type, Guid? correlationId) //{ // // Check if logging is enabled before creating log entries. // if (defaultWriter != null) // if (defaultWriter.IsLoggingEnabled()) // { // // initialize the correlationId if it is null // if (null == correlationId) // correlationId = Guid.NewGuid(); // var entry = new LogEntry { Message = msg, RelatedActivityId = correlationId }; // entry.Categories.Add(Defaults.DEFAULT_LOG_CATEGORY.ToString()); // entry.Severity = type; // entry.Title = Defaults.DEFAULT_LOG_TITLE; // // priority // entry.Priority = Defaults.DEFAULT_LOG_PRIORITY; // // Create a LogEntry using the constructor parameters. // defaultWriter.Write(entry); // } // else // { // Trace.WriteLine("Logging is disabled in the configuration."); // } // else // Trace.WriteLine("Logging is disabled in the configuration. Invalid Log Writter."); //} /// <summary> /// Logs the specified MSG. /// </summary> /// <param name="msg">The MSG.</param> /// <param name="correlationId">The correlation id.</param> //public static void Log(string msg, Guid? correlationId) //{ // // Check if logging is enabled before creating log entries. // if (DefaultWriter.IsLoggingEnabled()) // { // var entry = new LogEntry { Message = msg }; // entry.RelatedActivityId = correlationId; // entry.Categories.Add(Defaults.DEFAULT_LOG_CATEGORY.ToString()); // entry.Severity = Defaults.DEFAULT_TRACEEVENT_TYPE; // entry.Title = Defaults.DEFAULT_LOG_TITLE; // // priority // entry.Priority = Defaults.DEFAULT_LOG_PRIORITY; // // Create a LogEntry using the constructor parameters. // defaultWriter.Write(entry); // } // else // { // Trace.WriteLine("Logging is disabled in the configuration."); // } //} /// <summary> /// Traces the data. /// </summary> /// <param name="msg">The MSG.</param> //public static void TraceData(string msg) //{ // TraceData(msg, Guid.NewGuid(), 10, TraceEventType.Verbose); //} /// <summary> /// Traces the data. /// </summary> /// <param name="msg">The MSG.</param> /// <param name="correlationId">The correlation id.</param> /// <param name="priority">The priority.</param> /// <param name="tracetype">The tracetype.</param> public static void TraceData(string msg, Guid? correlationId, int priority, TraceEventType tracetype) { if (DefaultWriter.IsLoggingEnabled()) { Debug.WriteLineIf(outputDebug, msg); var entry = new LogEntry { Message = msg }; entry.RelatedActivityId = correlationId; if (correlationId.HasValue) entry.ActivityId = (Guid)correlationId; entry.Categories.Add(Defaults.DEFAULT_LOG_CATEGORY.ToString()); entry.Severity = tracetype; entry.Title = Defaults.DEFAULT_LOG_TITLE; entry.Priority = priority; DefaultWriter.Write(entry); } else { Trace.WriteLine(String.Format( "COLME: [{3}] [{2}] CORRID: [{1}] MSG: {0}", msg, correlationId, priority, tracetype.ToString() )); } }
void WriteAll(TraceEventCache eventCache, TraceEventType eventType, int id, string message) { UpdateIndent(); WriteLine("{4}-[{0}] {1}({2}) {3}".With(eventCache.DateTime.ToString("u"), eventType.ToString(), id, message, eventCache.ThreadId)); }
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { string logEntry = string.Format(LogTag, DateTime.Now, eventType != TraceEventType.Information ? eventType.ToString() : string.Empty, source); WriteLine(string.Format("{0} {1}", logEntry, message, id)); }
public LogMessageModel(object message, string category, int priority, int eventId, TraceEventType severity, string title, IDictionary<string, object> properties) { this.messageField = message.ToString(); this.categoryField = category; this.priorityField = priority; this.eventIdField = eventId; this.severityField = severity.ToString(); this.titleField = title; if (properties == null) { properties = new Dictionary<string, object>(); } this.formattedMessageField = (from p in properties select new LogMessageKeyValuePair() { Name = p.Key, Value = p.Value.ToString() }).ToArray(); }
private void Verify(string message, TraceEventType eventType, int id) { Assert.IsTrue(!target.initializedInFailedMode, "Per current setup, listener is not expected to be initialized in the failed mode!"); // verify connection string got assigned Assert.AreEqual<string>(target.connectionString, connection.ConnectionString); Trace.WriteLine(String.Format("Parameters count: {0}", parametersList.Count)); Trace.WriteLine("Parameters:" + parametersList.Aggregate(String.Empty, (s, p) => s += p.ParameterName + ",")); connection.AssertWasCalled((c) => c.Open()); command.AssertWasCalled((c) => c.ExecuteNonQuery()); Assert.AreEqual<string>(paramsAggregateList, parametersList.Aggregate(String.Empty, (s, p) => s += p.ParameterName + ",")); //target.connectionStringProvider.AssertWasCalled((p) => p[target.connectionStringName]); Assert.IsTrue(parametersList.Find((p) => { return p.ParameterName == "Date"; }).Value != null); Assert.AreEqual<int>(Convert.ToInt32(parametersList.Find((p) => { return p.ParameterName == "MessageId"; }).Value), id); Assert.AreEqual<int>(Convert.ToInt32(parametersList.Find((p) => { return p.ParameterName == "TypeId"; }).Value), (int)eventType); Assert.AreEqual<string>(parametersList.Find((p) => { return p.ParameterName == "TypeName"; }).Value.ToString(), eventType.ToString()); Assert.AreEqual<string>(parametersList.Find((p) => { return p.ParameterName == "MachineName"; }).Value.ToString(), Environment.MachineName); Assert.AreEqual<string>(parametersList.Find((p) => { return p.ParameterName == "Message"; }).Value.ToString(), message); }
private void WriteHeader(string source, TraceEventType eventType, int id) { this.Write(string.Format(CultureInfo.InvariantCulture, "{0} {1}: {2} : ", new object[] { source, eventType.ToString(), id.ToString(CultureInfo.InvariantCulture) })); }
private static string FormatSeverity(TraceEventType severity) { switch (severity) { case TraceEventType.Critical: return "Critical"; case TraceEventType.Error: return "Error"; case TraceEventType.Information: return "Information"; case TraceEventType.Verbose: return "Verbose"; case TraceEventType.Warning: return "Warning"; default: return severity.ToString(); } }
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")); }
private void WriteHeader(String source, TraceEventType eventType, int id) { switch (eventType) { case TraceEventType.Critical: color = Color.Maroon; break; case TraceEventType.Stop: case TraceEventType.Error: color = Color.Red; break; case TraceEventType.Resume: break; case TraceEventType.Start: color = Color.Green; break; case TraceEventType.Transfer: color = Color.MediumTurquoise; break; case TraceEventType.Suspend: case TraceEventType.Warning: color = Color.GreenYellow; break; } var str = String.Format(CultureInfo.InvariantCulture, "{0} {1}: {2} : ", source, eventType.ToString(), id.ToString(CultureInfo.InvariantCulture)); Write(str); color = Color.Black; }