/// <summary>
        /// Override this method to catch the event when a command is about to be executed.
        /// </summary>
        /// <param name="command">Command being executed</param>
        protected override void OnCommandExecuting(SqlCommand command)
        {
            if (command == null)
            {
                return;
            }
            var sb = new StringBuilder();

            if (command.Connection != null)
            {
                sb.AppendFormat("Connection: {0}\r\n", command.Connection.ConnectionString);
            }
            sb.AppendFormat("{0}\r\n", command.CommandText);
            foreach (SqlParameter par in command.Parameters)
            {
                sb.AppendFormat("  {0} ({1}): <'{2}'>\r\n", par.ParameterName, par.SqlDbType, par.Value);
            }
            var logItem = new TraceLogItem
            {
                OperationType = "SQLCommand",
                Type          = TraceLogItemType.Informational,
                Message       = sb.ToString()
            };

            Tracer.Log(logItem);
        }
Example #2
0
        /// <summary>
        /// Naplózza az adott bejegyzést
        /// </summary>
        /// <param name="item">Naplóbejegyzés</param>
        public static void Log(TraceLogItem item)
        {
            try
            {
                if (LoggerInstance == null || (int)item.Type < (int)s_LogType)
                {
                    return;
                }

                // --- Az üzenetben lévő sorvégeket lecseréljük
                if (item.Message != null)
                {
                    item.Message = item.Message.Replace("\r\n", "\n");
                    item.Message = item.Message.Replace("\n", "\r\n\t\t\t\t\t");
                }
                if (item.DetailedMessage != null)
                {
                    item.DetailedMessage = item.DetailedMessage.Replace("\r\n", "\n");
                    item.DetailedMessage = item.DetailedMessage.Replace("\n", "\r\n\t\t\t\t\t\t");
                }

                // --- Naplózzuk az üzenetet
                LoggerInstance.Log(item);
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception)
            {
                // --- A naplózásban levő kivételt lenyeljük
            }
        }
Example #3
0
        /// <summary>
        /// Log the specified message to the secondary event log
        /// </summary>
        /// <param name="eventClass">Event parameters</param>
        /// <param name="finalMessage">Message to log</param>
        private static void LogToSecondary(LogEventBase eventClass, string finalMessage)
        {
            var itemType = TraceLogItemType.Informational;

            switch (eventClass.Type)
            {
            case EventLogEntryType.FailureAudit:
            case EventLogEntryType.Error:
                itemType = TraceLogItemType.Error;
                break;

            case EventLogEntryType.Warning:
                itemType = TraceLogItemType.Warning;
                break;

            case EventLogEntryType.SuccessAudit:
                itemType = TraceLogItemType.Success;
                break;
            }
            var logItem = new TraceLogItem
            {
                Message         = finalMessage,
                DetailedMessage = String.Format("EventId: {0}, CategoryId: {1}",
                                                eventClass.EventId, eventClass.CategoryId),
                OperationType = "Windows Event Trace",
                Type          = itemType
            };

            TraceLogger.Log(logItem);
        }
 /// <summary>
 /// Override to specify how the trace entry should be logged.
 /// </summary>
 /// <param name="item">Trace entry</param>
 protected override void DoLog(TraceLogItem item)
 {
     using (var db = new SqlDatabase(_sqlConnectionOrName))
     {
         var logRecord = new TraceRecord
         {
             // ReSharper disable PossibleInvalidOperationException
             Timestamp = item.TimestampUtc.Value,
             // ReSharper restore PossibleInvalidOperationException
             Type                  = (int)item.Type,
             OperationType         = item.OperationType,
             SessionId             = item.SessionId,
             BusinessTransactionId = item.BusinessTransactionId,
             OperationInstanceId   = item.OperationInstanceId,
             TenantId              = item.TenantId,
             Message               = item.Message,
             DetailedMessage       = item.DetailedMessage,
             ServerName            = item.ServerName,
             // ReSharper disable PossibleInvalidOperationException
             ThreadId = item.ThreadId.Value
                        // ReSharper restore PossibleInvalidOperationException
         };
         db.Insert(logRecord);
     }
 }
        public void SingleScenarioWorks()
        {
            // --- Arrange
            var tracer    = new FileTraceLogger(LOG_FILE, LOG_ROOT, flushAfter: 3);
            var traceItem = new TraceLogItem
            {
                TimestampUtc  = new DateTime(2012, 1, 1, 8, 0, 0),
                Type          = TraceLogItemType.Informational,
                ServerName    = "Server",
                ThreadId      = 123,
                OperationType = "TestOp",
                Message       = "Message"
            };

            // --- Act
            for (var i = 0; i < 5; i++)
            {
                tracer.Log(traceItem);
            }
            tracer.Dispose();

            // --- Assert
            var text  = File.ReadAllText(Path.Combine(LOG_ROOT, LOG_FILE));
            var lines = text.Split(new [] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var line in lines)
            {
                line.ShouldContain("Informational\tServer\t123\tTestOp\tMessage\t");
            }
            lines.ShouldHaveCountOf(5);
        }
        /// <summary>
        /// This method is called before the body of the aspected method is about to be
        /// invoked.
        /// </summary>
        /// <param name="args">Descriptor representing the method call</param>
        /// <param name="result">Result descriptor coming from the previous aspect.</param>
        /// <returns>
        /// This method should return null value indicating that the aspected method's body should
        /// be called. If the method body invocation should be omitted, this method returns the
        /// result descriptor substituting the result coming from the invocation of the method body.
        /// </returns>
        public override IMethodResultDescriptor OnEntry(IMethodCallDescriptor args, IMethodResultDescriptor result)
        {
            if (args.Method.DeclaringType == typeof(IServiceObject))
            {
                return(null);
            }

            CallContext.LogicalSetData(START_TICK_LABEL, EnvironmentInfo.GetCurrentDateTimeUtc().Ticks);
            var details    = new StringBuilder();
            var traceAttrs = args.Method.GetCustomAttributes(typeof(NoArgumentTraceAttribute), true);

            if (traceAttrs.Length == 0)
            {
                for (var i = 0; i < args.ArgumentCount; i++)
                {
                    var arg     = args.GetArgument(i);
                    var argJson = JsonConvert.SerializeObject(arg.Value);
                    details.AppendFormat("{0}: {1}\r\n", arg.Name, argJson);
                }
            }

            var logItem = new TraceLogItem
            {
                Type            = TraceLogItemType.Informational,
                OperationType   = GetOperationName(args),
                Message         = "Enter",
                DetailedMessage = details.ToString()
            };

            Tracer.Log(logItem);
            return(null);
        }
Example #7
0
 public void Log(TraceLogItemType type, string operationType, string message, string detailedMessage = null)
 {
     var item = new TraceLogItem
         {
             Type = type,
             OperationType = operationType,
             Message = message,
             DetailedMessage = detailedMessage
         };
     Log(item);
 }
Example #8
0
        public static void Log(TraceLogItemType type, string operationType, string message, string detailedMessage = null)
        {
            var item = new TraceLogItem
            {
                Type            = type,
                OperationType   = operationType,
                Message         = message,
                DetailedMessage = detailedMessage
            };

            Log(item);
        }
        /// <summary>
        /// This method is called right after <see cref="IMethodAspect.OnExit"/>, when the method body
        /// invocation raised an exception. Otherwise, the <see cref="IMethodAspect.OnSuccess"/> method is
        /// called.
        /// </summary>
        /// <param name="args">Message representing the method call</param>
        /// <param name="exceptionRaised">Exception raised by the method body</param>
        /// <returns>Exception instance to be raised by the caller of the aspected method</returns>
        public override Exception OnException(IMethodCallDescriptor args, Exception exceptionRaised)
        {
            if (args.Method.DeclaringType == typeof(IServiceObject))
            {
                return(null);
            }

            var logItem = new TraceLogItem
            {
                Type            = TraceLogItemType.Error,
                OperationType   = GetOperationName(args),
                Message         = "Exception",
                DetailedMessage = exceptionRaised.ToString()
            };

            Tracer.Log(logItem);
            return(exceptionRaised);
        }
Example #10
0
        /// <summary>
        /// Raises the exception event.
        /// </summary>
        /// <param name="context">The context for the action.</param>
        public override void OnException(HttpActionExecutedContext context)
        {
            // --- Log this information to the trace log
            var logItem = new TraceLogItem
            {
                Type            = TraceLogItemType.Error,
                OperationType   = "WebAPI",
                Message         = "Exception",
                DetailedMessage = context.Exception.ToString()
            };

            Tracer.Log(logItem);

            var businessEx = context.Exception as BusinessOperationException;

            if (businessEx != null)
            {
                // --- This is a business issue
                var info = new BusinessExceptionInfo
                {
                    reasonCode  = businessEx.ReasonCode,
                    isBusiness  = true,
                    message     = businessEx.Message,
                    errorObject = businessEx.Notifications.Items
                };
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(info))
                });
            }

            // --- This is an infrastructure issue
            var infraInfo = new InfrastructureExceptionInfo
            {
                reasonCode = "Unexpected",
                isBusiness = false,
                message    = context.Exception.Message
            };

            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent(JsonConvert.SerializeObject(infraInfo))
            });
        }
Example #11
0
        /// <summary>
        /// This method is called right after <see cref="IMethodAspect.OnExit"/>, when the method body
        /// invocation was successful. Otherwise, the <see cref="IMethodAspect.OnException"/> method is
        /// called.
        /// </summary>
        /// <param name="args">Descriptor representing the method call</param>
        /// <param name="result">Result descriptor representing the return values of the call</param>
        /// <returns>
        /// This method should return the value of <paramref name="result"/> by default, or it
        /// can modify the original result on return that value.
        /// </returns>
        public override IMethodResultDescriptor OnSuccess(IMethodCallDescriptor args, IMethodResultDescriptor result)
        {
            if (args.Method.DeclaringType == typeof(IServiceObject))
            {
                return(null);
            }

            var startTimeData = CallContext.GetData(START_TICK_LABEL);
            var timeSpan      = startTimeData == null
                ? (TimeSpan?)null
                : TimeSpan.FromTicks(EnvironmentInfo.GetCurrentDateTimeUtc().Ticks - (long)startTimeData);

            var logItem = new TraceLogItem
            {
                Type            = TraceLogItemType.Success,
                OperationType   = GetOperationName(args),
                Message         = "Exit",
                DetailedMessage = string.Format("({0} ms)",
                                                timeSpan.HasValue ? timeSpan.Value.Milliseconds.ToString(CultureInfo.InvariantCulture) : "??")
            };

            Tracer.Log(logItem);
            return(result);
        }
        public void ComplexScenarioWorks()
        {
            // --- Arrange
            if (File.Exists(Path.Combine(LOG_ROOT, "08", LOG_FILE)))
            {
                File.Delete(Path.Combine(LOG_ROOT, "08", LOG_FILE));
            }
            if (File.Exists(Path.Combine(LOG_ROOT, "09", LOG_FILE)))
            {
                File.Delete(Path.Combine(LOG_ROOT, "09", LOG_FILE));
            }
            var tracer     = new FileTraceLogger(LOG_FILE, LOG_ROOT, "hh", flushAfter: 3);
            var traceItem1 = new TraceLogItem
            {
                // 8 o'clock
                TimestampUtc  = new DateTime(2012, 1, 1, 8, 0, 0),
                Type          = TraceLogItemType.Informational,
                ServerName    = "Server",
                ThreadId      = 123,
                OperationType = "TestOp",
                Message       = "Message"
            };
            var traceItem2 = new TraceLogItem
            {
                // 9 o'clock
                TimestampUtc  = new DateTime(2012, 1, 1, 9, 0, 0),
                Type          = TraceLogItemType.Informational,
                ServerName    = "Server",
                ThreadId      = 123,
                OperationType = "TestOp",
                Message       = "Message"
            };

            // --- Act
            for (var i = 0; i < 3; i++)
            {
                tracer.Log(traceItem1);
                tracer.Log(traceItem2);
                tracer.Log(traceItem1);
                tracer.Log(traceItem1);
            }
            tracer.Dispose();

            // --- Assert
            var text1  = File.ReadAllText(Path.Combine(LOG_ROOT, "08", LOG_FILE));
            var lines1 = text1.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            lines1.ShouldHaveCountOf(9);
            foreach (var line in lines1)
            {
                line.ShouldContain("\tInformational\tServer\t123\tTestOp\tMessage\t");
            }
            var text2  = File.ReadAllText(Path.Combine(LOG_ROOT, "09", LOG_FILE));
            var lines2 = text2.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            lines2.ShouldHaveCountOf(3);
            foreach (var line in lines2)
            {
                line.ShouldContain("\tInformational\tServer\t123\tTestOp\tMessage\t");
            }
        }
Example #13
0
 /// <summary>
 /// Override to specify how the trace entry should be logged.
 /// </summary>
 /// <param name="item">Trace entry</param>
 protected abstract void DoLog(TraceLogItem item);
Example #14
0
 /// <summary>
 /// Logs the specified trace entry
 /// </summary>
 /// <param name="item">Trace entry</param>
 public void Log(TraceLogItem item)
 {
     item.EnsureProperties();
     DoLog(item);
 }
Example #15
0
 /// <summary>
 /// Override to specify how the trace entry should be logged.
 /// </summary>
 /// <param name="item">Trace entry</param>
 protected abstract void DoLog(TraceLogItem item);
Example #16
0
 /// <summary>
 /// Logs the specified trace entry
 /// </summary>
 /// <param name="item">Trace entry</param>
 public void Log(TraceLogItem item)
 {
     item.EnsureProperties();
     DoLog(item);
 }