Exemplo n.º 1
0
        public async Task Current()
        {
            // Arrange
            EnhancedStackTrace est = null;

            // Act
            await Task.Run(() => est = EnhancedStackTrace.Current()).ConfigureAwait(false);

            // Assert
            var stackTrace = est.ToString();

            stackTrace = LineEndingsHelper.RemoveLineEndings(stackTrace);
            var trace = stackTrace.Split(new[] { Environment.NewLine }, StringSplitOptions.None)
                        // Remove Full framework entries
                        .Where(s => !s.StartsWith("   at bool System.Threading._ThreadPoolWaitCallbac") &&
                               !s.StartsWith("   at void System.Threading.Tasks.Task.System.Thre"));


            Assert.Equal(
                new[] {
                "   at bool System.Threading.ThreadPoolWorkQueue.Dispatch()"
            },
                trace);
        }
Exemplo n.º 2
0
        public ContainerBuilder InitContainer()
        {
            var assemblies = AssemblyUtils.GetAppAssemblies();

            PrintHeader();
            EnhancedStackTrace.Current();
            InitPolly();
            ServicesInfo     = new ObservableCollection <ServiceInfo>();
            ContainerBuilder = new ContainerBuilder();



            ContainerBuilder.RegisterModule(new LogRequestModule());
            ContainerBuilder.RegisterInstance(_neonConfig);
            ContainerBuilder.RegisterInstance <IServicesManager>(this);
            InitManagers();


            ContainerBuilder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces();
            AssemblyUtils.GetAppAssemblies().ForEach(a =>
            {
                ContainerBuilder
                .RegisterAssemblyTypes(a)
                .AsClosedTypesOf(typeof(IRequestHandler <,>))
                .AsImplementedInterfaces().SingleInstance();;

                ContainerBuilder
                .RegisterAssemblyTypes(a)
                .AsClosedTypesOf(typeof(INotificationHandler <>))
                .AsImplementedInterfaces().SingleInstance();
            });

            // It appears Autofac returns the last registered types first
            ContainerBuilder.RegisterGeneric(typeof(RequestPostProcessorBehavior <,>)).As(typeof(IPipelineBehavior <,>));
            ContainerBuilder.RegisterGeneric(typeof(RequestPreProcessorBehavior <,>)).As(typeof(IPipelineBehavior <,>));

            ContainerBuilder.Register <ServiceFactory>(ctx =>
            {
                var c = ctx.Resolve <IComponentContext>();
                return(t => c.Resolve(t));
            });

            var singletonServices = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(SingletonAttribute));
            var transientServices = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(TransientAttribute));
            var scopedServices    = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(ScopedAttribute));
            var dataAccess        = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(DataAccessAttribute));
            var luaObjects        = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(ScriptObjectAttribute));
            var jobObjects        = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(SchedulerJobTaskAttribute));
            var dbSeedsObject     = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(DatabaseSeedAttribute));
            var componentsObject  = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(ComponentAttribute));
            var noSqlConnectors   = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(NoSqlConnectorAttribute));
            var scriptEngines     = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(ScriptEngineAttribute));

            _availableServices = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(ServiceAttribute));


            _logger.LogDebug($"Services  {_availableServices.Count}");
            _logger.LogDebug($"Singleton services {singletonServices.Count}");
            _logger.LogDebug($"Transient services {transientServices.Count}");
            _logger.LogDebug($"Scoped services {scopedServices.Count}");
            _logger.LogDebug($"DataAccesses  {dataAccess.Count}");


            luaObjects.ForEach(l => { ContainerBuilder.RegisterType(l).AsSelf().SingleInstance(); });
            singletonServices.ForEach(t => RegisterService(LifeScopeTypeEnum.SINGLETON, t));
            componentsObject.ForEach(t => RegisterService(LifeScopeTypeEnum.SINGLETON, t));
            scriptEngines.ForEach(s => RegisterService(LifeScopeTypeEnum.SINGLETON, s));

            ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray())
            .Where(t => t == typeof(IDatabaseSeed))
            .AsImplementedInterfaces()
            .SingleInstance();

            ContainerBuilder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
            .Where(t => t == typeof(IDataAccess <>))
            .AsImplementedInterfaces()
            .SingleInstance();

            ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray())
            .AsClosedTypesOf(typeof(IDataAccess <>)).AsImplementedInterfaces();

            ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray())
            .AsClosedTypesOf(typeof(AbstractDataAccess <>)).AsImplementedInterfaces();

            ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray())
            .AsClosedTypesOf(typeof(IDtoMapper <,>)).AsImplementedInterfaces();

            ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray())
            .AsClosedTypesOf(typeof(AbstractDtoMapper <,>)).AsImplementedInterfaces();


            dataAccess.ForEach(d =>
            {
                ContainerBuilder.RegisterType(d).As(AssemblyUtils.GetInterfaceOfType(d)).InstancePerLifetimeScope();
            });

            noSqlConnectors.ForEach(t => { ContainerBuilder.RegisterType(t).InstancePerDependency(); });

            transientServices.ForEach(t => RegisterService(LifeScopeTypeEnum.TRANSIENT, t));

            dbSeedsObject.ForEach(t => { ContainerBuilder.RegisterType(t).AsSelf().InstancePerLifetimeScope(); });

            scopedServices.ForEach(t => RegisterService(LifeScopeTypeEnum.SCOPED, t));

            jobObjects.ForEach(t => RegisterService(LifeScopeTypeEnum.SCOPED, t));

            ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray())
            .Where(t => t.Name.ToLower().EndsWith("service"))
            .AsImplementedInterfaces().SingleInstance();


            //ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray())
            //	.Where(t => t.Name.ToLower().EndsWith("component"))
            //	.AsImplementedInterfaces().SingleInstance();


            return(ContainerBuilder);
        }
Exemplo n.º 3
0
        public void End()
        {
            if (Duration.HasValue)
            {
                _logger.Trace()
                ?.Log("Ended {Span} (with Duration already set)." +
                      " Start time: {Time} (as timestamp: {Timestamp}), Duration: {Duration}ms",
                      this, TimeUtils.FormatTimestampForLog(Timestamp), Timestamp, Duration);
            }
            else
            {
                Assertion.IfEnabled?.That(!_isEnded,
                                          $"Span's Duration doesn't have value even though {nameof(End)} method was already called." +
                                          $" It contradicts the invariant enforced by {nameof(End)} method - Duration should have value when {nameof(End)} method exits" +
                                          $" and {nameof(_isEnded)} field is set to true only when {nameof(End)} method exits." +
                                          $" Context: this: {this}; {nameof(_isEnded)}: {_isEnded}");

                var endTimestamp = TimeUtils.TimestampNow();
                Duration = TimeUtils.DurationBetweenTimestamps(Timestamp, endTimestamp);
                _logger.Trace()
                ?.Log("Ended {Span}. Start time: {Time} (as timestamp: {Timestamp})," +
                      " End time: {Time} (as timestamp: {Timestamp}), Duration: {Duration}ms",
                      this, TimeUtils.FormatTimestampForLog(Timestamp), Timestamp,
                      TimeUtils.FormatTimestampForLog(endTimestamp), endTimestamp, Duration);
            }

            var isFirstEndCall = !_isEnded;

            _isEnded = true;

            if (ShouldBeSentToApmServer && isFirstEndCall)
            {
                try
                {
                    DeduceDestination();
                }
                catch (Exception e)
                {
                    _logger.Warning()?.LogException(e, "Failed deducing destination fields for span.");
                }

                // Spans are sent only for sampled transactions so it's only worth capturing stack trace for sampled spans
                // ReSharper disable once CompareOfFloatsByEqualityOperator
                if (ConfigSnapshot.StackTraceLimit != 0 && ConfigSnapshot.SpanFramesMinDurationInMilliseconds != 0)
                {
                    if (Duration >= ConfigSnapshot.SpanFramesMinDurationInMilliseconds ||
                        ConfigSnapshot.SpanFramesMinDurationInMilliseconds < 0)
                    {
                        if (_stackFrames == null)
                        {
                            StackFrame[] trace;
                            var          stackTrace = new StackTrace(true);
                            try
                            {
                                // I saw EnhancedStackTrace throwing exceptions in some environments
                                // therefore we try-catch and fall back to a non-demystified call stack.
                                trace = new EnhancedStackTrace(stackTrace).GetFrames();
                            }
                            catch
                            {
                                trace = stackTrace.GetFrames();
                            }

                            StackTrace = StacktraceHelper.GenerateApmStackTrace(trace,
                                                                                _logger,
                                                                                ConfigSnapshot, _apmServerInfo, $"Span `{Name}'");
                        }
                        else
                        {
                            StackTrace = StacktraceHelper.GenerateApmStackTrace(_stackFrames,
                                                                                _logger,
                                                                                ConfigSnapshot, _apmServerInfo, $"Span `{Name}'");
                        }
                    }
                }

                _payloadSender.QueueSpan(this);
            }

            if (isFirstEndCall)
            {
                _currentExecutionSegmentsContainer.CurrentSpan = _parentSpan;
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// 抛出异常.
 /// </summary>
 /// <param name="code">Code.</param>
 /// <param name="title">Title.</param>
 /// <param name="messages">Messages.</param>
 /// <returns>Friendly Exception.</returns>
 public static FriendlyException ThrowException(int code, string title, params string[] messages)
 {
     return(new FriendlyException(code, EnhancedStackTrace.Current(), title, messages));
 }
Exemplo n.º 5
0
 protected override StackTrace CreateStackTrace(Exception exception) =>
 exception == null
         ? EnhancedStackTrace.Current()
         : new EnhancedStackTrace(exception);
        public void RelativePathIsConvertedToAnAbsolutePath(string original, string expected)
        {
            var converted = EnhancedStackTrace.TryGetFullPath(original);

            Assert.Equal(expected, NormalizePath(converted));
        }