private TraceData ( System eventType, int id ) : void | ||
eventType | System | |
id | int | |
return | void |
public virtual void TraceData(TraceEventType eventType, int id, object data) { Execute(() => { var args = enricher.Enrich(new[] { data }, true); traceSource.TraceData(eventType, id, args); }); }
protected void submitCodeBehindButton_Click(object sender, EventArgs e) { System.Diagnostics.TraceSource source = new System.Diagnostics.TraceSource(sourceTextBox.Text); source.TraceData(System.Diagnostics.TraceEventType.Error, 100, "Test from the code behind"); }
private async Task <HttpResponseMessage> LogResponse(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken, System.Diagnostics.TraceSource fallbackTraceSource, Stopwatch sw) { var response = await base.SendAsync(request, cancellationToken); if (response == null || response.Content == null) { return(response); } var responseContent = await response.Content.ReadAsStringAsync(); try { sw.Stop(); var statusCode = (int)response.StatusCode; var responseHeaders = response.Content.Headers.ToString() + " " + response.Headers.ToString(); responseTraceSource.TraceResponse( (int)response.StatusCode, responseHeaders, responseContent, sw.ElapsedMilliseconds); } catch (Exception exp) { fallbackTraceSource.TraceData(TraceEventType.Error, (int)Event.LoggingExceptionFallingBack, exp); } return(response); }
public void TestLogException() { try { throw new Exception("First inner exception"); } catch (Exception firstInnerException) { try { throw new Exception("Second inner exception", firstInnerException); } catch (Exception secondInnerException) { try { throw new Exception("Outermost exception.", secondInnerException); } catch (Exception ex) { ex.Data.Add("UnitTest", "SqlTraceListenerTest"); var traceSource = new TraceSource("TestTraceSource"); traceSource.TraceData(TraceEventType.Error, 1979, ex); } } } }
private void TraceToOutput() { TraceSource traceSource = new TraceSource("TraceSource", SourceLevels.All); traceSource.TraceInformation("Tracing"); traceSource.TraceEvent(TraceEventType.Critical, 0, "Critical"); traceSource.TraceData(TraceEventType.Information, 1, new object[] { "x", "y", "z" }); traceSource.Flush(); traceSource.Close(); }
protected void Application_Start(Object sender, EventArgs e) { TaskScheduler.UnobservedTaskException += ( object sender2, UnobservedTaskExceptionEventArgs args) => { var trace = new TraceSource("UnhandledExceptionTrace Tasks"); trace.TraceData(TraceEventType.Error, 1, args.Exception); args.SetObserved(); }; }
public static void Main(string[] args) { TraceSource traceSource = new TraceSource("myTraceSource", SourceLevels.All); traceSource.TraceInformation("Tracing application..."); traceSource.TraceEvent(TraceEventType.Critical, 0, "Critical trace"); traceSource.TraceData(TraceEventType.Information, 1, new object[] { "a", "b", "c" }); traceSource.Flush(); traceSource.Close(); }
public void TestTraceSourceLogging() { TraceSource source = new TraceSource("TestOfIoCXmlRollingWriter"); for (int i = 0; i < 100000; i++) { source.TraceData(TraceEventType.Information, i, "test of test data"); source.Flush(); } source.Flush(); }
public static void HowToUseTheTraceSourceClass() { TraceSource traceSource = new TraceSource("myTraceSource", SourceLevels.All); traceSource.TraceInformation("Tracing app"); traceSource.TraceEvent(TraceEventType.Critical, 0, "Critical trace"); traceSource.TraceData(TraceEventType.Information, 1, new object[] { "a", "b", "c" }); traceSource.Flush(); traceSource.Close(); }
protected void Execute(Action action) { try { action(); } catch (Exception exp) { fallbackTraceSource.TraceData(TraceEventType.Error, (int)Event.LoggingExceptionFallingBack, exp); } }
public void FormatterListenerAsString() { FormattedDatabaseTraceListener listener = new FormattedDatabaseTraceListener(new SqlDatabase(connectionString), "WriteLog", "AddCategory", new TextFormatter("TEST{newline}TEST")); // need to go through the source to get a TraceEventCache TraceSource source = new TraceSource("notfromconfig", SourceLevels.All); source.Listeners.Add(listener); source.TraceData(TraceEventType.Error, 0, "test message"); string messageContents = GetLastLogMessage("LoggingDb"); Assert.AreEqual("test message", messageContents); }
internal static void TraceData(TraceSource source, TraceEventType eventType, Enum eventId, object data) { try { source.TraceData(eventType, Convert.ToInt32(eventId), data); } catch (Exception ex) { Console.Write(ex.ToString()); // will get into standard output then // this is the lowest fallback possible (SD) } }
static void Main(string[] args) { TraceSource traceSource = new TraceSource("myTraceSource", SourceLevels.All); traceSource.TraceInformation("Tracing application."); traceSource.TraceEvent(TraceEventType.Critical, 0, "Critical trace"); traceSource.TraceData(TraceEventType.Information, 1, new object[] { "a", "b", "c" }); traceSource.Flush(); traceSource.Close(); Console.WriteLine("Press a key to exit"); Console.ReadKey(); }
public void OnActionExecuting(ActionExecutingContext filterContext) { try { var currentRequest = filterContext.HttpContext.Request; if (IsExcluded(currentRequest.Url.ToString())) { return; } SetupTimer(filterContext.HttpContext.ApplicationInstance.Context); var requestContent = currentRequest.ToRaw(); requestTraceSource.TraceRequest( currentRequest.HttpMethod, SerializationHelper.GetObjectContent(currentRequest.Headers.ToDictionary()), requestContent); } catch (Exception exp) { fallbackTraceSource.TraceData(TraceEventType.Error, (int)Event.LoggingExceptionFallingBack, exp); } }
private async Task LogRequest(HttpRequestMessage request, System.Diagnostics.TraceSource fallbackTraceSource) { var requestContent = await request.Content.ReadAsStringAsync(); try { var requestHeaders = request.Headers.ToDictionary(k => k.Key, v => v.Value); requestTraceSource.TraceRequest( request.Method.ToString(), GetRequestHeaders(request), requestContent); } catch (Exception exp) { fallbackTraceSource.TraceData(TraceEventType.Error, (int)Event.LoggingExceptionFallingBack, exp); } }
public static void HowToUseTheTraceListenerClass() { Stream outputFile = File.Create("traceFile.txt"); TextWriterTraceListener textListener = new TextWriterTraceListener(outputFile); TraceSource traceSource = new TraceSource("myTraceSource", SourceLevels.All); traceSource.Listeners.Clear(); traceSource.Listeners.Add(textListener); traceSource.TraceInformation("Tracing app"); traceSource.TraceEvent(TraceEventType.Critical, 0, "Critical trace"); traceSource.TraceData(TraceEventType.Information, 1, new object[] { "a", "b", "c" }); traceSource.Flush(); traceSource.Close(); }
public static void Trace(object[] data, string traceSourceName) { try { string sourceName = !String.IsNullOrEmpty(traceSourceName) ? traceSourceName : ModuleConfiguration.DefaultTraceSourceName; System.Diagnostics.TraceSource trace = new System.Diagnostics.TraceSource(sourceName); trace.TraceData(System.Diagnostics.TraceEventType.Information, new Random().Next(), data); trace.Flush(); } catch (Exception) { //If you want to handle this exception, add your exception handling code here, else you may uncomment the following line to throw this exception out. throw; } }
static void Main(string[] args) { Debug.WriteLine("Starting application"); Debug.Indent(); int i = 1 + 2; Debug.Assert(i == 3); Debug.WriteLineIf(i > 0, "i is greater than 0"); TraceSource traceSource = new TraceSource("myTraceSource", SourceLevels.All); traceSource.TraceInformation("Tracing application.."); traceSource.TraceEvent(TraceEventType.Critical, 0, "Critical trace"); traceSource.TraceData(TraceEventType.Information, 1, new object[] { "a", "b", "c" }); traceSource.Flush(); traceSource.Close(); DoTrace(); Console.ReadLine(); }
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { var allParameters = GetParams(); _columnMap = allParameters.Where(a => a.Name.StartsWith(ColumnMap.ColumnRename, StringComparison.OrdinalIgnoreCase)); var parameters = allParameters.Except(_columnMap, new ColumnMapComparer()); foreach (var parameter in parameters) { // dapper 1.7+ rips off the @, this allows for either @ or no prefix to be found and replaced var name = parameter.Name.StartsWith(ColumnMap.Parameter, StringComparison.OrdinalIgnoreCase) ? parameter.Name : ColumnMap.Parameter + parameter.Name; _command.CommandText = _command.CommandText.Replace(name, parameter.Value.ToString()); } var trace = new System.Diagnostics.TraceSource("mdx"); trace.TraceData(System.Diagnostics.TraceEventType.Information, 0, _command.CommandText); var results = PopulateFromXml(_command.ExecuteXmlReader()); return(behavior == CommandBehavior.CloseConnection ? new MdxDataReader(results, _connection) : new MdxDataReader(results)); }
private void StartScope() { // Log Transfer In (on original activity) Guid newActivity = Guid.NewGuid(); if (_source != null) { _source.TraceTransfer(_transferInId, _transferInMessage, newActivity); } // Change to scope ActivityId Trace.CorrelationManager.ActivityId = newActivity; // Log Start Message (first message on scope activity) if (_source != null) { if (_activityName == null) { _source.TraceEvent(TraceEventType.Start, _startId, _startMessage); } else { //var xml = string.Format(TraceRecordXmlTemplate, // SecurityElement.Escape(_startMessage), // SecurityElement.Escape(AppDomain.CurrentDomain.FriendlyName), // SecurityElement.Escape(_activityName) //); var xml = TraceRecordXmlTemplate; var doc = new XmlDocument(); doc.LoadXml(xml); doc.ChildNodes[0].ChildNodes[1].InnerText = _startMessage; doc.ChildNodes[0].ChildNodes[2].InnerText = AppDomain.CurrentDomain.FriendlyName; doc.ChildNodes[0].ChildNodes[3].ChildNodes[0].InnerText = _activityName; _source.TraceData(TraceEventType.Start, _startId, doc.CreateNavigator()); } } }
internal static void TraceData(TraceSource source, TraceEventType eventType, Enum eventId, object data) { source.TraceData(eventType, Convert.ToInt32(eventId), data); }
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { var allParameters = GetParams(); _columnMap = allParameters.Where(a => a.Name.StartsWith(ColumnMap.ColumnRename, StringComparison.OrdinalIgnoreCase)); var parameters = allParameters.Except(_columnMap, new ColumnMapComparer()); foreach (var parameter in parameters) { // dapper 1.7+ rips off the @, this allows for either @ or no prefix to be found and replaced var name = parameter.Name.StartsWith(ColumnMap.Parameter, StringComparison.OrdinalIgnoreCase) ? parameter.Name : ColumnMap.Parameter + parameter.Name; _command.CommandText = _command.CommandText.Replace(name, parameter.Value.ToString()); } var trace = new System.Diagnostics.TraceSource("mdx"); trace.TraceData(System.Diagnostics.TraceEventType.Information, 0, _command.CommandText); var results = PopulateFromXml(_command.ExecuteXmlReader()); return behavior == CommandBehavior.CloseConnection ? new MdxDataReader(results, _connection) : new MdxDataReader(results); }
public void LogToEmailUsingDirectObjectOnlyResultsInOneMessage() { MockEmailTraceListener listener = new MockEmailTraceListener("[email protected];[email protected]", "*****@*****.**", "EntLib-Logging ->", "has occurred", "smtphost"); TraceSource source = new TraceSource("unnamed", SourceLevels.All); source.Listeners.Add(listener); int numMessages = listener.MessagesSent; source.TraceData(TraceEventType.Error, 1, new TestCustomObject()); source.Close(); int newNumMessages = listener.MessagesSent; Assert.AreEqual(numMessages, newNumMessages - 1); }
public void TraceDataTests() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = new TraceSource("MySource1", SourceLevels.All); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceData(TraceEventType.Critical, 123, 42); AssertDebugLastMessage("debug", "MySource1 Fatal 42 123"); ts.TraceData(TraceEventType.Critical, 145, 42, 3.14, "foo"); AssertDebugLastMessage("debug", "MySource1 Fatal 42, 3.14, foo 145"); }
public void LogWithMultipleCategories() { FormattedDatabaseTraceListener listener = new FormattedDatabaseTraceListener(new SqlDatabase(connectionString), "WriteLog", "AddCategory", new TextFormatter("TEST{newline}TEST")); // need to go through the source to get a TraceEventCache TraceSource source = new TraceSource("notfromconfig", SourceLevels.All); source.Listeners.Add(listener); LogEntry logEntry = new LogEntry(); logEntry.Message = "message"; logEntry.Categories.Add("FormattedCategory"); logEntry.Categories.Add("DictionaryCategory"); logEntry.EventId = 123; logEntry.Priority = 11; logEntry.Severity = TraceEventType.Error; logEntry.Title = "title"; source.TraceData(TraceEventType.Error, 0, logEntry); DatabaseProviderFactory factory = new DatabaseProviderFactory(ConfigurationSourceFactory.Create()); Data.Database db = factory.CreateDefault(); DbCommand command = db.GetSqlStringCommand("SELECT Count(*) FROM Category"); int categoryCount = Convert.ToInt32(db.ExecuteScalar(command)); Assert.AreEqual(2, categoryCount); }
static void Main(string[] args) { Configuration.Configuration configuration = Configuration.Configuration.GetConfiguration(); string node = configuration.Node; string dc = configuration.Dc; Publisher publisher = new Publisher(dc); TraceSource source = new TraceSource("Health.Checks"); foreach (PowerShellCheckItem item in PowerShellCheckFactory.Initialize(@"C:\Projects\Toyota.Tsusho\Health\Health.Tests\Checks").Values) { using (new TraceLogicalScope(source, String.Format("Processing {0}.", item.Configuration.Id))) { if (!item.Configuration.Disabled) { List<string> validationErrors = new List<string>(); item.Check.Validate(validationErrors); if (validationErrors.Count > 0) { foreach (string error in validationErrors) source.TraceData(TraceEventType.Warning, 0, error); throw new Exception("The Check contains validation errors."); } var ob = Observable.Create<CheckResult>((IObserver<CheckResult> observer) => { return Scheduler.Default.Schedule(item.Configuration.Interval, recursive => { CheckResult result = item.Check.Execute(); item.Check.PreviousStatus = item.Check.Status; item.Check.Status = result.Status; //We only push data if the status has changed if (item.Check.Status != item.Check.PreviousStatus) observer.OnNext(item.Check.Execute()); recursive(item.Configuration.Interval); }); }); ob.Subscribe((CheckResult result) => { CheckEvent ev = new CheckEvent() { Created = DateTime.Now, Id = item.Configuration.Id, Message = result.Message, Node = node, Notes = result.Notes, Source = Environment.MachineName, Status = result.Status }; publisher.Publish(ev); }); } } } Console.ReadLine(); }
public void FormatterListenerWithWrongStoredProcs() { FormattedDatabaseTraceListener listener = new FormattedDatabaseTraceListener(new SqlDatabase(connectionString), "WrongWriteLog", "AddCategory", new TextFormatter("TEST{newline}TEST")); TraceSource source = new TraceSource("notfromconfig", SourceLevels.All); source.Listeners.Add(listener); source.TraceData(TraceEventType.Error, 0, new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null)); }
public void LogToDatabaseUsingDirectObjectOnlyResultsInOneMessage() { FormattedDatabaseTraceListener listener = new FormattedDatabaseTraceListener(new SqlDatabase(connectionString), "WriteLog", "AddCategory", new TextFormatter("TEST{newline}TEST")); TraceSource source = new TraceSource("notfromconfig", SourceLevels.All); source.Listeners.Add(listener); int numMessages = GetNumberOfLogMessage("LoggingDb"); source.TraceData(TraceEventType.Error, 1, new TestCustomObject()); source.Close(); int newNumMessages = GetNumberOfLogMessage("LoggingDb"); Assert.AreEqual(numMessages, newNumMessages - 1); }
internal void Start() { Microsoft.ServiceBus.ServiceBusEnvironment.SystemConnectivity.Mode = Microsoft.ServiceBus.ConnectivityMode.Http; string node = configuration.Node; string dc = configuration.Dc; this.publisher = new Publisher(dc); TraceSource source = new TraceSource("Health.Checks"); string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), dc, "Checks"); source.TraceData(TraceEventType.Verbose, 0, "Path", path); foreach (PowerShellCheckItem item in PowerShellCheckFactory.Initialize(path).Values) { using (new TraceLogicalScope(source, String.Format("Processing {0}.", item.Configuration.Id))) { if (!item.Configuration.Disabled) { List<string> validationErrors = new List<string>(); item.Check.Validate(validationErrors); if (validationErrors.Count > 0) { foreach (string error in validationErrors) source.TraceData(TraceEventType.Warning, 0, error); throw new Exception("The Check contains validation errors."); } var ob = Observable.Create<CheckResult>((IObserver<CheckResult> observer) => { return Scheduler.Default.Schedule(item.Configuration.Interval, recursive => { CheckResult result = item.Check.Execute(); item.Check.PreviousStatus = item.Check.Status; item.Check.Status = result.Status; //We only push data if the status has changed if (item.Check.Status != item.Check.PreviousStatus) observer.OnNext(result); recursive(item.Configuration.Interval); }); }); ob.Subscribe((CheckResult result) => { CheckEvent ev = new CheckEvent() { Created = DateTime.Now, Id = item.Configuration.Id, Message = result.Message, Node = node, Notes = result.Notes, Source = Environment.MachineName, Status = result.Status }; publisher.Publish(ev); }); } } } Console.ReadLine(); }
public void FormatterListenerWithStoredProcsAndDbInstance() { FormattedDatabaseTraceListener listener = new FormattedDatabaseTraceListener(new SqlDatabase(connectionString), "WriteLog", "AddCategory", new TextFormatter("TEST{newline}TEST")); // need to go through the source to get a TraceEventCache TraceSource source = new TraceSource("notfromconfig", SourceLevels.All); source.Listeners.Add(listener); source.TraceData(TraceEventType.Error, 0, new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null)); string messageContents = GetLastLogMessage("LoggingDb"); Assert.AreEqual("TEST" + Environment.NewLine + "TEST", messageContents); }
internal static void TraceData(TraceSource traceSource, TraceEventType traceEventType, int p, Exception ex) { traceSource.TraceData(traceEventType, p, ex.ToString()); }
internal static void TraceData(TraceSource traceSource, TraceEventType traceEventType, int p, string data) { traceSource.TraceData(traceEventType, p, data); }
private static void LogError(string tracesource, int id, string message) { TraceSource TraceSource = new TraceSource(tracesource); TraceSource.TraceData(TraceEventType.Error, id, message); TraceSource.Close(); }
internal MethodProfiler(TraceSource source, params object[] data) { source.TraceData(TraceEventType.Start, 0, data); _disposal = delegate() { source.TraceData(TraceEventType.Stop, 0, data); }; }
public void ShouldFilterLog() { MockEmailTraceListener listener = new MockEmailTraceListener("[email protected];[email protected]", "*****@*****.**", "EntLib-Logging ->", "has occurred", "smtphost"); listener.Filter = new EventTypeFilter(SourceLevels.Warning); TraceSource source = new TraceSource("unnamed", SourceLevels.Error); source.Listeners.Add(listener); source.TraceData(TraceEventType.Information, 1, new TestCustomObject()); source.Close(); Assert.AreEqual(0, listener.MessagesSent); }
public void LogToMsmqUsingDirectObjectOnlyResultsInOneMessage() { ILogFormatter formatter = new BinaryLogFormatter(); MsmqTraceListener listener = new MsmqTraceListener("unnamed", CommonUtil.MessageQueuePath, formatter, MessagePriority.Low, true, MsmqTraceListenerData.DefaultTimeToBeReceived, MsmqTraceListenerData.DefaultTimeToReachQueue, false, false, false, MsmqTraceListenerData.DefaultTransactionType, new MockMsmqInterfaceFactory()); TraceSource source = new TraceSource("unnamed", SourceLevels.All); source.Listeners.Add(listener); int numMessages = MockMsmqInterface.Instance.MessageCount; source.TraceData(TraceEventType.Error, 1, new TestCustomObject()); source.Close(); int newNumMessages = MockMsmqInterface.Instance.MessageCount; Assert.AreEqual(numMessages, newNumMessages - 1); }
public ActivityScope(TraceSource source, int transferInId, int startId, int transferOutId, int stopId, string transferInMessage, string startMessage, string transferOutMessage, string stopMessage, string activityName) { _source = source; _startId = startId; _stopId = stopId; _transferInId = transferInId; _transferOutId = transferOutId; _previousActivityId = Trace.CorrelationManager.ActivityId; _transferInMessage = transferInMessage; _startMessage = startMessage; _transferOutMessage = transferOutMessage; _stopMessage = stopMessage; // Log Transfer In Guid newActivity = Guid.NewGuid(); if (_source != null) { _source.TraceTransfer(_transferInId, _transferInMessage ?? ActivityScope_Transfer, newActivity); } Trace.CorrelationManager.ActivityId = newActivity; // Log Start Message if (_source != null) { var xml = string.Format(@"<TraceRecord Severity='Start' xmlns='http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord'> <TraceIdentifier></TraceIdentifier> <Description>{0}</Description> <AppDomain>{1}</AppDomain> <ExtendedData xmlns='http://schemas.microsoft.com/2006/08/ServiceModel/DictionaryTraceRecord'> <ActivityName>{2}</ActivityName> <ActivityType>Construct</ActivityType> </ExtendedData> </TraceRecord>", _startMessage ?? ActivityScope_Start, AppDomain.CurrentDomain.FriendlyName, activityName ?? _startMessage ?? ActivityScope_Start ); var doc = new XmlDocument(); doc.LoadXml(xml); _source.TraceData(TraceEventType.Start, _startId, doc.CreateNavigator()); } }