Esempio n. 1
0
        protected void WriteTrace(TraceRecord record)
        {
            var message = string.Format("{0};{1};{2}", record.Operator, record.Operation, record.Message);
            //System.Diagnostics.Trace.WriteLine(message, record.Category);
            System.Diagnostics.Trace.WriteLine(message, record.Category);

            switch (record.Level)
            {
                case TraceLevel.Error:
                    _traceSource.TraceEvent(TraceEventType.Error, 0, message);
                    break;
                case TraceLevel.Fatal:
                    _traceSource.TraceEvent(TraceEventType.Critical, 0, message);
                    break;
                case TraceLevel.Warn:
                    _traceSource.TraceEvent(TraceEventType.Warning, 0, message);
                    break;
                case TraceLevel.Debug:
                    _traceSource.TraceEvent(TraceEventType.Verbose, 0, message);
                    break;
                default:
                    _traceSource.TraceEvent(TraceEventType.Information, 0, message); //record.Request
                    break;
            }
        }
Esempio n. 2
0
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            var record = new TraceRecord(request, category, level);
            traceAction(record);

            var sb = new StringBuilder();
            if (record.Request != null)
            {
                if (record.Request.Method != null)
                {
                    sb.Append(" ");
                    sb.Append(request.Method.ToString());
                }
                if (record.Request.RequestUri != null)
                {
                    sb.Append(" ");
                    sb.Append(record.Request.RequestUri.ToString());
                }
                if (!string.IsNullOrWhiteSpace(record.Category))
                {
                    sb.Append(" ");
                    sb.Append(record.Category);
                }
                sb.Append(" ");
                sb.Append(record.Message);

                if (record.Exception != null)
                {
                    sb.Append(record.Exception.ToString());
                }
            }
            Console.WriteLine(sb.ToString());
        }
        private static string Log(TraceRecord record)
        {
            var message = new StringBuilder();

            if (record.Request != null)
            {
                if (record.Request.Method != null)
                    message.Append(record.Request.Method);

                if (record.Request.RequestUri != null)
                    message.Append(" ").Append(record.Request.RequestUri.AbsoluteUri);
            }

            if (!string.IsNullOrWhiteSpace(record.Category))
                message.Append(" ").Append(record.Category);

            if (!string.IsNullOrWhiteSpace(record.Operator))
                message.Append(" ").Append(record.Operator).Append(" ").Append(record.Operation);

            if (!string.IsNullOrWhiteSpace(record.Message))
                message.Append(" ").Append(record.Message);

            if (record.Exception != null && !string.IsNullOrWhiteSpace(record.Exception.GetBaseException().Message))
            message.Append(" ").Append(record.Exception.GetBaseException().Message);

            return string.Format("{0} {1}", record.Level, message);
        }
Esempio n. 4
0
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            if (category == null)
            {
                throw new ArgumentNullException("category");
            }

            if (traceAction == null)
            {
                throw new ArgumentNullException("traceAction");
            }

            if (level < TraceLevel.Off || level > TraceLevel.Fatal)
            {
                throw new ArgumentOutOfRangeException("level");
            }

            TraceRecord traceRecord = new TraceRecord(request, category, level);
            traceAction(traceRecord);
            string message = Format(traceRecord);
            if (!String.IsNullOrEmpty(message))
            {
                _logger.WriteCore(eventType: TraceLevelToTraceEventType[(int)traceRecord.Level], eventId: 0, state: null, exception: traceRecord.Exception, formatter: (_state, _ex) =>
                {
                    return Format(traceRecord);
                });
            }
        }
        private void Log(TraceRecord record)
        {
            var message = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(record.Message))
                message.Append("").Append(record.Message + Environment.NewLine);

            if (record.Request != null)
            {
                if (record.Request.Method != null)
                    message.Append("Method: " + record.Request.Method + Environment.NewLine);

                if (record.Request.RequestUri != null)
                    message.Append("").Append("URL: " + record.Request.RequestUri + Environment.NewLine);

                if (record.Request.Headers != null && record.Request.Headers.Contains("Token") && record.Request.Headers.GetValues("Token") != null && record.Request.Headers.GetValues("Token").FirstOrDefault() != null)
                    message.Append("").Append("Token: " + record.Request.Headers.GetValues("Token").FirstOrDefault() + Environment.NewLine);
            }

            if (!string.IsNullOrWhiteSpace(record.Category))
                message.Append("").Append(record.Category);

            if (!string.IsNullOrWhiteSpace(record.Operator))
                message.Append(" ").Append(record.Operator).Append(" ").Append(record.Operation);

            if (record.Exception != null && !string.IsNullOrWhiteSpace(record.Exception.GetBaseException().Message))
            {
                var exceptionType = record.Exception.GetType();
                message.Append(Environment.NewLine);
                message.Append("").Append("Error: " + record.Exception.GetBaseException().Message + Environment.NewLine);
            }

            Logger[record.Level](Convert.ToString(message) + Environment.NewLine);
        }
        private void Log(TraceRecord record)
        {
            var message = new StringBuilder();

            if (record.Request != null)
            {
                if (record.Request.Method != null)
                    message.Append(" ").Append(record.Request.Method.Method);

                if (record.Request.RequestUri != null)
                    message.Append(" ").Append(record.Request.RequestUri.AbsoluteUri);
            }

            if (!string.IsNullOrWhiteSpace(record.Category))
                message.Append(" ").Append(record.Category);

            if (!string.IsNullOrWhiteSpace(record.Operator))
                message.Append(" ").Append(record.Operator).Append(" ").Append(record.Operation);

            if (!string.IsNullOrWhiteSpace(record.Message))
                message.Append(" ").Append(record.Message);
                  
            if (record.Exception != null && !string.IsNullOrEmpty(record.Exception.GetBaseException().Message))
                message.Append(" ").AppendLine(record.Exception.GetBaseException().Message);

            Logger[record.Level](message.ToString());
        }
Esempio n. 7
0
 public void Trace(HttpRequestMessage request, string category, TraceLevel traceLevel,
     Action<TraceRecord> traceAction)
 {
     var record = new TraceRecord(request, category, traceLevel);
     traceAction(record);
     WriteTrace(record);
 }
Esempio n. 8
0
 protected void WriteTrace(TraceRecord rec)
 {
     var message = string.Format("{0} {1} {2}", rec.Operator, rec.Operation, rec.Message);
     switch (rec.Level)
     {
         case TraceLevel.Debug:
             Engine.Logger.Debug(message);
             break;
         case TraceLevel.Error:
             Engine.Logger.Error(message);
             break;
         case TraceLevel.Fatal:
             Engine.Logger.Fatal(message);
             break;
         case TraceLevel.Info:
             Engine.Logger.Info(message);
             break;
         case TraceLevel.Off:
             // Do nothing?
             break;
         case TraceLevel.Warn:
             Engine.Logger.Warn(message);
             break;
        
     }
  
     System.Diagnostics.Trace.WriteLine(message, rec.Category);
 }
        public void Trace(
            HttpRequestMessage request,
            string category,
            TraceLevel level,
            Action<TraceRecord> traceAction)
        {
            var trace = new TraceRecord(request, category, level);
            traceAction(trace);

            _traces.Enqueue(trace);

            var context = GlobalHost.ConnectionManager.GetConnectionContext<TracePersistentConnection>();
            context.Groups.Send(
                TracePersistentConnection.Authenticated,
                new
                {
                    trace.RequestId,
                    trace.Request.RequestUri,
                    Status = trace.Status.ToString(),
                    Level = trace.Level.ToString(),
                    trace.Message,
                    trace.Category,
                    TimeTicks = trace.Timestamp.Ticks,
                    trace.Operator,
                    trace.Operation,
                    Exception = trace.Exception == null ? "" : trace.Exception.Message,
                });
        }
Esempio n. 10
0
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            if (TraceSwitcher.Level == TraceSwitcher.TraceLevel.None)
                return;

            if (request == null)
                return;

            var rec = new TraceRecord(request, category, level);
            traceAction(rec);
            AddTraceData(request, rec);

            if (!IsRequestFinishing(rec))
                return;

            var traceData = GetTraceData(request);
            if (traceData != null)
            {
                ComputeSummaryData(traceData);

                if (TraceSwitcher.Level == TraceSwitcher.TraceLevel.Error
                    && traceData.Exception == null)
                {
                    return;
                }

                OnRequestFinish(traceData);
            }
        }
Esempio n. 11
0
 protected void WriteTrace(TraceRecord rec)
 {
     var message = string.Format("{0};{1};{2}",
                                 rec.Operator, rec.Operation, rec.Message);
     System.Diagnostics.Trace.WriteLine(message, rec.Category);
     Log.Debug(rec.Category + " " + message);
 }
Esempio n. 12
0
        /// <summary>
        /// Performs the start trace operation.
        /// </summary>
        /// <param name="traceRecord">The <see cref="TraceRecord">trace record</see> associated with the operation.</param>
        public void StartTrace( TraceRecord traceRecord )
        {
            Arg.NotNull( traceRecord, nameof( traceRecord ) );

            Start();
            startTrace( traceRecord );
        }
Esempio n. 13
0
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            var record = new TraceRecord(request, category, level);
            traceAction(record);

            System.Diagnostics.Trace.TraceInformation("{0} {1} {2}", category, level, record.Message);
        }
Esempio n. 14
0
        private void Log(TraceRecord record)
        {
            var message = string.Empty;

            if (record.Request != null)
            {
                if (record.Request.Method != null)
                    message += " " + record.Request.Method.ToString();

                if (record.Request.RequestUri != null)
                    message += " " + record.Request.RequestUri.ToString();
            }

            if (!string.IsNullOrWhiteSpace(record.Category))
                message += " " + record.Category;

            if (!string.IsNullOrWhiteSpace(record.Operator))
                message += " " + record.Operator + " " + record.Operation;

            if (!string.IsNullOrWhiteSpace(record.Message))
                message += " " + record.Message;

            if (record.Exception != null)
            {
                if (record.Exception.GetBaseException().Message != null)
                    message += record.Exception.GetBaseException().Message;
            }

            _logger[record.Level](message);
        }
Esempio n. 15
0
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            // set nlog logger - note: this category is bypassed; the logger name in the log event info is used instead
            var logger = LogManager.GetLogger(category);

            try
            {
                // only log and trace if enabled
                var logLevel = GetLogLevel(level);
                if (logger.IsEnabled(logLevel))
                {
                    // setup trace record
                    var record = new TraceRecord(request, category, level);

                    // user traces and populates record
                    traceAction(record);

                    // create the log event and log  - this will log to the configured nlog target, rules, etc. specified by the app
                    logger.Log(CreateEvent(record, logLevel));
                }
            }
            catch(Exception e)
            {
                // log exception - this exception usually occurs within the user's trace action code                
                logger.LogException(LogLevel.Error, "Failed to trace message due to an error.", e);
                throw;
            }
        }
        private void WriteXmlElement(TraceRecord rec)
        {
            using (Stream xmlFile = new FileStream(@"D:\Ari Gunawan\Belajar\WEB API\Code\Apress.PracticalWebApi.HelloWebApi\log.xml", FileMode.Append))
            {
                using (XmlTextWriter writer = new XmlTextWriter(xmlFile, Encoding.UTF8))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.WriteStartElement("trace");
                    writer.WriteElementString("timestamp", rec.Timestamp.ToString());
                    writer.WriteElementString("operation", rec.Operation);
                    writer.WriteElementString("user", rec.Operator);

                    if (!String.IsNullOrWhiteSpace(rec.Message))
                    {
                        writer.WriteStartElement("message");
                        writer.WriteCData(rec.Message);
                        writer.WriteEndElement();
                    }

                    writer.WriteElementString("category", rec.Category);
                    writer.WriteEndElement();
                    writer.WriteString(Environment.NewLine);
                    writer.Flush();
                }
            }
        }
Esempio n. 17
0
 protected void WriteTrace(TraceRecord rec)
 {
     var message = string.Format("{0};{1};{2}",
         rec.Operator, rec.Operation, rec.Message);
     //System.Diagnostics.Trace.WriteLine(message, rec.Category);
     log.TraceFormat("Category {0} - {1}", rec.Category,message);
 }
Esempio n. 18
0
        /// <summary>
        /// Adds a single trace record to the store.
        /// </summary>
        /// <remarks>
        /// All trace records are correlated with their associated
        /// request GUID inside this method.
        /// </remarks>
        /// <param name="traceRecord"></param>
        public void AddTrace(TraceRecord traceRecord)
        {
            lock (_thisLock)
            {
                RequestTrace requestTrace;
                if (_requestList.Count >= _maxRequests)
                {
                    requestTrace = _requestList.Last.Value;
                    _requestList.RemoveLast();
                    _requestDictionary.Remove(requestTrace.Id);
                }

                if (!_requestDictionary.TryGetValue(traceRecord.RequestId.ToString(), out requestTrace))
                {
                    requestTrace = CreateRequestTrace(traceRecord);
                    _requestDictionary[requestTrace.Id] = requestTrace;
                    _requestList.AddFirst(requestTrace);
                }

                TraceItem traceItem = CreateTraceItem(traceRecord);
                requestTrace.Traces.Add(traceItem);
                if (traceItem.Status != 0)
                {
                    requestTrace.Status = traceItem.Status;
                    requestTrace.Reason = ((HttpStatusCode) traceItem.Status).ToString();
                }
            }
        }
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            if (request != null)
            {
                var traceQueryString = request.GetQueryString("trace"); ;

                bool shouldTrace;
                if (traceQueryString != null &&  Boolean.TryParse(traceQueryString, out shouldTrace)&& shouldTrace)
            {
                    object perRequestTrace;
                    if (!request.Properties.TryGetValue("perRequestTrace", out perRequestTrace))
                    {
                        perRequestTrace = new List<string>();
                        request.Properties["perRequestTrace"] = perRequestTrace;
                    }

                    var record = new TraceRecord(request, category, level);
                    traceAction(record);
                    (perRequestTrace as List<string>).Add(Log(record));
                }
            }

            if (_innerWriter != null)
            {
                _innerWriter.Trace(request, category, level, traceAction);
            }
        }
Esempio n. 20
0
        private void Log(TraceRecord traceRecord) {

            IDependencyScope dependencyScope = traceRecord.Request.GetDependencyScope();
            ILoggerService loggerService = dependencyScope.GetService(typeof(ILoggerService)) as ILoggerService;

            loggerService.Log(new HttpApiLogRecord {
                CorrelationId = traceRecord.RequestId,
                RequestUri = traceRecord.Request.RequestUri.ToString(),
                IpAddress = traceRecord.Request.GetUserHostAddress(),
                HttpMethod = traceRecord.Request.Method.ToString(),
                UserAgent = traceRecord.Request.Headers.UserAgent.ToString(),
                Category = traceRecord.Category,
                Level = traceRecord.Level.ToString(),
                Kind = traceRecord.Kind.ToString(),
                Operator = traceRecord.Operator,
                Operation = traceRecord.Operation,
                ResponseStatusCode = traceRecord.Status.GetHashCode(),
                LogMessage = traceRecord.Message,
                ExceptionType = traceRecord.Exception != null ? traceRecord.Exception.GetType().ToString() : null,
                BaseExceptionType = traceRecord.Exception != null ? traceRecord.Exception.GetBaseException().GetType().ToString() : null,
                ExceptionMessage = traceRecord.Exception != null ? traceRecord.Exception.Message : null,
                ExceptionStackTrace = traceRecord.Exception != null ? traceRecord.Exception.StackTrace : null,
                Timestamp = traceRecord.Timestamp
            });
        }
Esempio n. 21
0
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            if (level == TraceLevel.Off) return;

            var record = new TraceRecord(request, category, level);
            traceAction(record);
            Log(record);
        }
Esempio n. 22
0
        /// <summary>
        /// Performs the start trace operation.
        /// </summary>
        /// <param name="traceRecord">The <see cref="TraceRecord">trace record</see> associated with the operation.</param>
        public void EndTrace( TraceRecord traceRecord )
        {
            Arg.NotNull( traceRecord, nameof( traceRecord ) );

            Stop();
            traceRecord.SetDuration( Elapsed );
            endTrace( traceRecord );
        }
Esempio n. 23
0
        public override void Trace(System.Net.Http.HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            if (traceAction == null) throw new ArgumentNullException("traceAction");

            var record = new TraceRecord(request, category, level);
            traceAction(record);
            WriteTrace(record);
        }
        /// <summary>
        /// Logs the trace.
        /// </summary>
        /// <param name="record">The trace record.</param>
        public virtual void LogTrace(TraceRecord record)
        {
            var method = record.Request != null ? record.Request.Method.Method : string.Empty;
            var uri = record.Request != null ? record.Request.RequestUri.AbsoluteUri : string.Empty;

            var message = string.Format("[{0}] {1}: {2} {3} {4}", record.Category, record.Kind, method, uri, string.IsNullOrEmpty(record.Message) ? string.Empty : " - " + record.Message);

            switch (record.Level)
            {
                case TraceLevel.Info:
                    this.logger.Info(message);
                    break;
                case TraceLevel.Debug:
                    this.logger.Debug(message);
                    break;
                case TraceLevel.Warn:
                    this.logger.Warn(message);
                    break;
                case TraceLevel.Error:
                    this.logger.Error(message);
                    break;
                case TraceLevel.Fatal:
                    this.logger.Fatal(message);
                    break;
            }

            // Add exception message if present
            if (record.Exception != null)
            {
                this.logger.Error(string.Format("{0}: {1}", record.Exception.Message, record.Exception.StackTrace));

                if (record.Exception.InnerException != null)
                {
                    this.logger.Error(string.Format("{0}: {1}", record.Exception.InnerException.Message, record.Exception.InnerException.StackTrace));    
                }
            }

            // Write to system.diagnostics as well
            System.Diagnostics.Trace.WriteLine(message, record.Category);

            // Calculate performance
            if (record.Kind == TraceKind.End)
            {
                var begin = this.beginTraces.ToList().FirstOrDefault(r =>
                        (record.RequestId == r.RequestId && record.Category == r.Category &&
                         record.Operation == r.Operation && record.Operator == r.Operator));


                if (begin != null)
                {
                    // Log performance
                    this.logger.Info(string.Format("[{0}] {1}: {2} {3} - Request processing time: {4} s", record.Category, record.Kind, method, uri, record.Timestamp - begin.Timestamp));

                    // Remove begintrace
                    this.beginTraces.Remove(begin);
                }
            }
        }
Esempio n. 25
0
 public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
 {
     TraceRecord traceRecord = new TraceRecord(request, category, level);
     traceAction(traceRecord);
     lock (_traceRecords)
     {
         _traceRecords.Add(traceRecord);
     }
 }
Esempio n. 26
0
        public void Trace(HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, Action <System.Web.Http.Tracing.TraceRecord> traceAction)
        {
            // Check if this log level is enabled in our Log4Net settings
            if (level == TraceLevel.Debug && log.IsDebugEnabled == false ||
                level == TraceLevel.Info && (log.IsInfoEnabled == false) ||
                level == TraceLevel.Warn && (log.IsWarnEnabled == false) ||
                level == TraceLevel.Error && (log.IsErrorEnabled == false) ||
                level == TraceLevel.Fatal && (log.IsFatalEnabled == false))
            {
                return;
            }

            // Create trace record and populate details
            var rec = new System.Web.Http.Tracing.TraceRecord(request, category, level);

            traceAction(rec);

            // Change unwanted "Info" traces to Debug
            if (rec.Level == TraceLevel.Info)
            {
                // Operation == "" on the first and last trace message
                if (rec.Operation == null || rec.Operation.Length > 0)
                {
                    rec.Level = TraceLevel.Debug;
                    // Return if we have changed this to debug and Log4Net doesn't have debug enabled
                    if (log.IsDebugEnabled == false)
                    {
                        return;
                    }
                }
            }

            var msg = String.Format("{0} {1} {2}", rec.RequestId, rec.Kind.ToString(), rec.Message);

            switch (rec.Level)
            {
            case TraceLevel.Debug:
                log.Debug(msg);
                break;

            case TraceLevel.Info:
                log.Info(msg);
                break;

            case TraceLevel.Warn:
                log.Warn(msg);
                break;

            case TraceLevel.Error:
                log.Error(msg, rec.Exception);
                break;

            case TraceLevel.Fatal:
                log.Fatal(msg, rec.Exception);
                break;
            }
        }
Esempio n. 27
0
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            TraceRecord rec = new TraceRecord(request, category, level);
            traceAction(rec);

            var message = string.Format("{0};{1};{2};{3}", rec.Category, rec.Operator, rec.Operation, rec.Message);

            _logger.Debug(message);
        }
 public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
 {
     if (level != TraceLevel.Off)
     {
         TraceRecord rec = new TraceRecord(request, category, level);
         traceAction(rec);
         WriteXmlElement(rec);
     }
 }
Esempio n. 29
0
 public void Trace(System.Net.Http.HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
 {
     if (level != TraceLevel.Off)
     {
         TraceRecord traceRecord = new TraceRecord(request, category, level);
         traceAction(traceRecord);
         Log(traceRecord);
     }
 }
        private void LogToSlab(TraceRecord record)
        {
            var message = new StringBuilder();
            AddRequestDataToMessage(record, message);
            AddRecordDataToMessage(record, message);

            var result = message.ToString();
            _exectueLogDict[record.Level].Invoke(result);
        }
Esempio n. 31
0
 public void Trace(HttpRequestMessage request, string category, TraceLevel level,
     Action<TraceRecord> traceAction)
 {
     if (Startup.TracingEnabled)
     {
         TraceRecord rec = new TraceRecord(request, category, level);
         traceAction(rec);
         WriteTrace(rec);
     }
 }
Esempio n. 32
0
        /// <summary>
        /// Examines the given <see cref="TraceRecord"/> to determine whether it
        /// contains an <see cref="HttpResponseException"/> and if so, modifies
        /// the <see cref="TraceRecord"/> to capture more detailed information.
        /// </summary>
        /// <param name="traceRecord">The <see cref="TraceRecord"/> to examine and modify.</param>
        public virtual void TranslateHttpResponseException(TraceRecord traceRecord)
        {
            if (traceRecord == null)
            {
                throw Error.ArgumentNull("traceRecord");
            }

            var httpResponseException = ExtractHttpResponseException(traceRecord);

            if (httpResponseException == null)
            {
                return;
            }

            HttpResponseMessage response = httpResponseException.Response;

            Contract.Assert(response != null);

            // If the status has been set already, do not overwrite it,
            // otherwise propagate the status into the record.
            if (traceRecord.Status == 0)
            {
                traceRecord.Status = response.StatusCode;
            }

            // Client level errors are downgraded to TraceLevel.Warn
            if ((int)response.StatusCode < (int)HttpStatusCode.InternalServerError)
            {
                traceRecord.Level = TraceLevel.Warn;
            }

            // Non errors are downgraded to TraceLevel.Info
            if ((int)response.StatusCode < (int)HttpStatusCode.BadRequest)
            {
                traceRecord.Level = TraceLevel.Info;
            }

            // HttpResponseExceptions often contain HttpError instances that carry
            // detailed information that may be filtered out by IncludeErrorDetailPolicy
            // before reaching the client. Capture it here for the trace.
            ObjectContent objectContent = response.Content as ObjectContent;

            if (objectContent == null)
            {
                return;
            }

            HttpError httpError = objectContent.Value as HttpError;

            if (httpError == null)
            {
                return;
            }

            object messageObject        = null;
            object messageDetailsObject = null;

            List <string> messages = new List <string>();

            if (httpError.TryGetValue(MessageKey, out messageObject))
            {
                messages.Add(Error.Format(SRResources.HttpErrorUserMessageFormat, messageObject));
            }

            if (httpError.TryGetValue(MessageDetailKey, out messageDetailsObject))
            {
                messages.Add(Error.Format(SRResources.HttpErrorMessageDetailFormat, messageDetailsObject));
            }

            // Extract the exception from this HttpError and then incrementally
            // walk down all inner exceptions.
            AddExceptions(httpError, messages);

            // ModelState errors are handled with a nested HttpError
            object modelStateErrorObject = null;

            if (httpError.TryGetValue(ModelStateKey, out modelStateErrorObject))
            {
                HttpError modelStateError = modelStateErrorObject as HttpError;
                if (modelStateError != null)
                {
                    messages.Add(FormatModelStateErrors(modelStateError));
                }
            }

            traceRecord.Message = String.Join(", ", messages);
        }
Esempio n. 33
0
 private static HttpResponseException ExtractHttpResponseException(TraceRecord traceRecord)
 {
     return(ExtractHttpResponseException(traceRecord.Exception));
 }
Esempio n. 34
0
        /// <summary>
        /// Examines the given <see cref="TraceRecord"/> to determine whether it
        /// contains an <see cref="HttpResponseException"/> and if so, modifies
        /// the <see cref="TraceRecord"/> to capture more detailed information.
        /// </summary>
        /// <param name="traceRecord">The <see cref="TraceRecord"/> to examine and modify.</param>
        public static void TranslateHttpResponseException(TraceRecord traceRecord)
        {
            Contract.Assert(traceRecord != null);

            HttpResponseException httpResponseException = ExtractHttpResponseException(
                traceRecord.Exception
                );

            if (httpResponseException == null)
            {
                return;
            }

            HttpResponseMessage response = httpResponseException.Response;

            Contract.Assert(response != null);

            // If the status has been set already, do not overwrite it,
            // otherwise propagate the status into the record.
            if (traceRecord.Status == 0)
            {
                traceRecord.Status = response.StatusCode;
            }

            traceRecord.Level = GetMappedTraceLevel(httpResponseException) ?? traceRecord.Level;

            // HttpResponseExceptions often contain HttpError instances that carry
            // detailed information that may be filtered out by IncludeErrorDetailPolicy
            // before reaching the client. Capture it here for the trace.
            ObjectContent objectContent = response.Content as ObjectContent;

            if (objectContent == null)
            {
                return;
            }

            HttpError httpError = objectContent.Value as HttpError;

            if (httpError == null)
            {
                return;
            }

            object messageObject        = null;
            object messageDetailsObject = null;

            List <string> messages = new List <string>();

            if (httpError.TryGetValue(HttpErrorKeys.MessageKey, out messageObject))
            {
                messages.Add(Error.Format(HttpErrorUserMessageFormat, messageObject));
            }

            if (httpError.TryGetValue(HttpErrorKeys.MessageDetailKey, out messageDetailsObject))
            {
                messages.Add(Error.Format(HttpErrorMessageDetailFormat, messageDetailsObject));
            }

            // Extract the exception from this HttpError and then incrementally
            // walk down all inner exceptions.
            AddExceptions(httpError, messages);

            // ModelState errors are handled with a nested HttpError
            object modelStateErrorObject = null;

            if (httpError.TryGetValue(HttpErrorKeys.ModelStateKey, out modelStateErrorObject))
            {
                HttpError modelStateError = modelStateErrorObject as HttpError;
                if (modelStateError != null)
                {
                    messages.Add(FormatModelStateErrors(modelStateError));
                }
            }

            traceRecord.Message = String.Join(", ", messages);
        }
Esempio n. 35
0
        /// <summary>
        /// Formats the given <see cref="TraceRecord"/> into a string describing
        /// either the initial receipt of the incoming request or the final send
        /// of the response, depending on <see cref="TraceKind"/>.
        /// </summary>
        /// <param name="traceRecord">The <see cref="TraceRecord"/> from which to
        /// produce the result.</param>
        /// <returns>A string containing comma-separated name-value pairs.</returns>
        public virtual string FormatRequestEnvelope(TraceRecord traceRecord)
        {
            if (traceRecord == null)
            {
                throw Error.ArgumentNull("traceRecord");
            }

            List <string> messages = new List <string>();

            if (IsVerbose)
            {
                messages.Add(
                    Error.Format(
                        (traceRecord.Kind == TraceKind.Begin)
                          ? SRResources.TimeRequestFormat
                          : SRResources.TimeResponseFormat,
                        FormatDateTime(traceRecord.Timestamp)
                        )
                    );
            }
            else
            {
                messages.Add(
                    (traceRecord.Kind == TraceKind.Begin)
                      ? SRResources.ShortRequestFormat
                      : SRResources.ShortResponseFormat
                    );
            }

            if (traceRecord.Status != 0)
            {
                messages.Add(
                    Error.Format(
                        SRResources.HttpStatusFormat,
                        (int)traceRecord.Status,
                        traceRecord.Status.ToString()
                        )
                    );
            }

            if (traceRecord.Request != null)
            {
                messages.Add(
                    Error.Format(SRResources.HttpMethodFormat, traceRecord.Request.Method)
                    );

                if (traceRecord.Request.RequestUri != null)
                {
                    messages.Add(
                        Error.Format(
                            SRResources.UrlFormat,
                            traceRecord.Request.RequestUri.ToString()
                            )
                        );
                }
            }

            if (IsVerbose)
            {
                messages.Add(Error.Format(SRResources.IdFormat, traceRecord.RequestId.ToString()));
            }

            // The Message and Exception fields do not contain interesting information unless
            // there is a problem, so they appear after the more informative trace information.
            if (!String.IsNullOrEmpty(traceRecord.Message))
            {
                messages.Add(Error.Format(SRResources.MessageFormat, traceRecord.Message));
            }

            if (traceRecord.Exception != null)
            {
                messages.Add(
                    Error.Format(SRResources.ExceptionFormat, traceRecord.Exception.ToString())
                    );
            }

            return(String.Join(", ", messages));
        }
Esempio n. 36
0
        /// <summary>
        /// Formats the contents of the given <see cref="TraceRecord"/> into
        /// a single string containing comma-separated name-value pairs
        /// for each <see cref="TraceRecord"/> property.
        /// </summary>
        /// <param name="traceRecord">The <see cref="TraceRecord"/> from which
        /// to produce the result.</param>
        /// <returns>A string containing comma-separated name-value pairs.</returns>
        public virtual string Format(TraceRecord traceRecord)
        {
            if (traceRecord == null)
            {
                throw Error.ArgumentNull("traceRecord");
            }

            // The first and last traces are injected by the tracing system itself.
            // We use these to format unique strings identifying the incoming request
            // and the outgoing response.
            if (
                String.Equals(
                    traceRecord.Category,
                    SystemWebHttpRequestCategory,
                    StringComparison.Ordinal
                    )
                )
            {
                return(FormatRequestEnvelope(traceRecord));
            }

            List <string> messages = new List <string>();

            if (!IsVerbose)
            {
                // In short format mode, we trace only End traces because it is
                // where the results of each operation will appear.
                if (traceRecord.Kind == TraceKind.Begin)
                {
                    return(null);
                }
            }
            else
            {
                messages.Add(
                    Error.Format(
                        SRResources.TimeLevelKindFormat,
                        FormatDateTime(traceRecord.Timestamp),
                        traceRecord.Level.ToString(),
                        traceRecord.Kind.ToString()
                        )
                    );

                if (!String.IsNullOrEmpty(traceRecord.Category))
                {
                    messages.Add(Error.Format(SRResources.CategoryFormat, traceRecord.Category));
                }

                messages.Add(Error.Format(SRResources.IdFormat, traceRecord.RequestId.ToString()));
            }

            if (!String.IsNullOrEmpty(traceRecord.Message))
            {
                messages.Add(Error.Format(SRResources.MessageFormat, traceRecord.Message));
            }

            if (traceRecord.Operator != null || traceRecord.Operation != null)
            {
                messages.Add(
                    Error.Format(
                        SRResources.OperationFormat,
                        traceRecord.Operator,
                        traceRecord.Operation
                        )
                    );
            }

            if (traceRecord.Status != 0)
            {
                messages.Add(
                    Error.Format(
                        SRResources.HttpStatusFormat,
                        (int)traceRecord.Status,
                        traceRecord.Status.ToString()
                        )
                    );
            }

            if (traceRecord.Exception != null)
            {
                messages.Add(
                    Error.Format(SRResources.ExceptionFormat, traceRecord.Exception.ToString())
                    );
            }

            return(String.Join(", ", messages));
        }