/// <summary>
        /// Add AbpFx Resource
        /// </summary>
        /// <param name="services"></param>
        /// <param name="virtualPath"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static II18NServiceCollection AddAbpResourceFrom(this II18NServiceCollection services, string virtualPath)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (string.IsNullOrWhiteSpace(virtualPath))
            {
                throw new ArgumentNullException(nameof(virtualPath));
            }

            var path = PathHelper.Combine(services.ExposeOptions, virtualPath, true);

            try {
                foreach (var filePath in PathHelper.GetSeveralPathList(path))
                {
                    using (var bridgeAdapter = new AbpJsonFileAdapter(filePath)) {
                        if (bridgeAdapter.Process())
                        {
                            var speaker = bridgeAdapter.Speak();
                            services.ExposeOptions.AddResource(speaker.PackageKey, TranslateResourceFactory.Create(speaker));
                        }
                    }
                }
            }
            catch (Exception exception) {
                InternalLogger.WriteLine($"Thrown exception when add json resource from {path}, message: {0}", exception.Message);
            }

            return(services);
        }
 private static void LogNonFormattableEvent(LogEvent logEvent, Exception e)
 {
     InternalLogger.WriteLine(
         "Event at {0} with message template {1} could not be formatted into JSON and will be dropped: {2}",
         logEvent.Timestamp.ToString("o"),
         logEvent.MessageTemplate.Text,
         e);
 }
Beispiel #3
0
        private void ParseAndInsertLogEventIntoQueueAutomatically(LogEventId eventId, LogEventLevel level, Exception exception, string messageTemplate,
                                                                  ILogCallerInfo callerInfo, LogEventContext context = null, params object[] messageTemplateParameters)
        {
            var task = CreateEnqueueTask();

            task.ContinueWith(t => DispatchForAutomatic());
            task.Start();

            Task CreateEnqueueTask()
            {
                var taskResult = new Task(async() => {
                    var writer = await _automaticAsyncQueue.AcquireWriteAsync(1, CancellationToken.None);
                    writer.Visit(
                        succeeded => {
                        _messageParameterProcessor.Process(messageTemplate, __as(messageTemplateParameters, context),
                                                           out var parsedTemplate, out var namedMessageProperties, out var positionalMessageProperties);

                        var logEvent = new LogEvent(StateNamespace, eventId, level, parsedTemplate, exception,
                                                    LogEventSendMode.Automatic, callerInfo, _upstreamRenderingOptions,
                                                    namedMessageProperties, positionalMessageProperties, context,
                                                    messageProcessorShortcut: _messageParameterProcessor);

                        if (succeeded.ItemCount >= 1)
                        {
                            _automaticAsyncQueue.ReleaseWrite(logEvent);
                        }
                        else
                        {
                            _automaticAsyncQueue.ReleaseWrite();
                        }

                        return(logEvent);
                    },
                        cancelled => {
                        InternalLogger.WriteLine("When insert log event(0) into async queue, task has been cancelled.");
                        return(null);
                    },
                        faulted => {
                        InternalLogger.WriteLine(
                            $@"Thrown an exception when insert log event(0) into async queue:{Environment.NewLine}{faulted.Exception.ToUnwrappedString()}",
                            faulted.Exception);
                        return(null);
                    });
                });

                return(taskResult);

                object[] __as(object[] __paramObjs, LogEventContext __context)
                {
                    if (__paramObjs == null || !__paramObjs.Any())
                    {
                        return(__context?.Parameters.ToArray());
                    }
                    return(__paramObjs.GetType() != typeof(object[]) ? new object[] { __paramObjs } : __paramObjs);
                }
            }
        }
     private static void ProcessError(HttpResponseMessage response, string uri)
     {
         if (!response.IsSuccessStatusCode)
         {
             InternalLogger.WriteLine(@"Tencent Cloud CLS call failed:
 Status Code  : {0}
 Request Uri  : {1}",
                                      response.StatusCode, uri);
         }
     }
Beispiel #5
0
     private static void ProcessError(PutResponse response)
     {
         if (response.Error != null)
         {
             InternalLogger.WriteLine(@"JD Cloud Log Service call failed:
 Request Id   : {0}
 Error Code   : {1}
 Error Message: {2}",
                                      response.RequestId, response.Error.Code, response.Error.Message);
         }
     }
Beispiel #6
0
     private static void ProcessError(IResponse response)
     {
         if (!response.IsSuccess)
         {
             InternalLogger.WriteLine(@"Aliyun SLS call failed:
 Request Id   : {0}
 Error Code   : {1}
 Error Message: {2}",
                                      response.RequestId, response.Error.ErrorCode, response.Error.ErrorMessage);
         }
     }
 void FlushToDisk(IFlushableAstronaut flushable)
 {
     try {
         if (Interlocked.CompareExchange(ref _flushRequired, 0, 1) == 1)
         {
             flushable.FlushToDisk();
         }
     }
     catch (Exception exception) {
         InternalLogger.WriteLine("{0} could not flush the underlying sink to disk: {1}", typeof(PeriodicAstronaut), exception);
     }
 }
 /// <summary>
 /// Add from stream
 /// </summary>
 /// <param name="stream"></param>
 public void AddFromStream(Stream stream)
 {
     try {
         var bf = new BinaryFormatter();
         if (bf.Deserialize(stream) is List <MessageTemplate> buffer)
         {
             AddInternal(buffer);
         }
     } catch {
         InternalLogger.WriteLine("Throw exception when deserialize stream to List<MessageTemplate>.");
     }
 }
 /// <summary>
 /// Create a new instance of <see cref="PeriodicAstronaut"/>.
 /// </summary>
 /// <param name="astronaut"></param>
 /// <param name="flushInterval"></param>
 public PeriodicAstronaut(IAstronaut astronaut, TimeSpan flushInterval)
 {
     _astronaut = astronaut ?? throw new ArgumentNullException(nameof(astronaut));
     if (_astronaut is IFlushableAstronaut flushable)
     {
         _timer = new Timer(_ => FlushToDisk(flushable), null, flushInterval, flushInterval);
     }
     else
     {
         _timer = new Timer(_ => { }, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
         InternalLogger.WriteLine("{0} configured to flush {1}, but {2} not implemented", typeof(PeriodicAstronaut), astronaut, nameof(IFlushableAstronaut));
     }
 }
Beispiel #10
0
        public static bool TryResolveCompilerGeneratedType(object value, PropertyResolvingMode mode, NestParameterResolver nest, Type typeOfValue,
                                                           bool raiseException, int positionalValue, out MessagePropertyValue result)
        {
            if (mode == PropertyResolvingMode.Destructure)
            {
                result = new StructureValue(StructureElements(), Tag());
                return(true);

                string Tag()
                {
                    var __tag = typeOfValue.Name;

                    if (string.IsNullOrWhiteSpace(__tag) || typeOfValue.IsCompilerGeneratedType())
                    {
                        __tag = null;
                    }
                    return(__tag);
                }

                IEnumerable <MessageProperty> StructureElements()
                {
                    foreach (var property in value.GetType().GetPropertiesRecursive())
                    {
                        dynamic propertyValue;
                        try {
                            propertyValue = property.GetValue(value);
                        }
                        catch (TargetParameterCountException) {
                            InternalLogger.WriteLine("The property accessor '{0}' is a non-default indexer", property);
                            continue;
                        }
                        catch (TargetInvocationException ex) {
                            InternalLogger.WriteLine("The property accessor '{0}' threw exception: {1}", property, ex);
                            if (raiseException)
                            {
                                throw;
                            }
                            propertyValue = $"Threw an exception at: {ex.InnerException?.GetType().Name}";
                        }

                        yield return(new MessageProperty(property.Name, positionalValue, nest.CreatePropertyValue(propertyValue, PropertyResolvingMode.Destructure)));
                    }
                }
            }

            result = null;
            return(false);
        }
Beispiel #11
0
        private static II18NServiceCollection AddXmlAnonymousResourceFromOnce(II18NServiceCollection services, string path, bool referenceToBasePath)
        {
            try {
                using (var adapter = new AnonymousXmlFileAdapter(PathHelper.Combine(services.ExposeOptions, path, referenceToBasePath))) {
                    if (adapter.Process())
                    {
                        var speaker = adapter.Speak();
                        services.ExposeOptions.AddAnonymousResource(TranslateResourceFactory.Create(speaker));
                    }
                }
            }
            catch (Exception exception) {
                InternalLogger.WriteLine($"Thrown exception when add json resource from {path}, message: {0}", exception.Message);
            }

            return(services);
        }
        public static void Handle(HttpApplication application)
        {
            if (application == null)
            {
                return;
            }

            var logger = StaticServiceResolver.Instance.GetLogger <HttpApplication>();

            var exception  = application.Server.GetLastError();
            var statusCode = application.Response.StatusCode;

            if (statusCode >= 500)
            {
                var realException = exception.Unwrap();
                var paramObj      = new {
                    FxName               = Constants.AspNetMvcName,
                    UsedTime             = Constants.Unknown,
                    StatusCode           = statusCode,
                    ExceptionDetails     = exception.Message,
                    ExceptionType        = exception.GetType(),
                    ExceptionMessage     = exception.Message,
                    RealExceptionType    = realException.GetType(),
                    RealExceptionMessage = realException.Message,
                };
                logger.LogFatal(exception, WebTemplateStandard.WebLog500, paramObj);
            }
            else if (statusCode >= 400)
            {
                var paramObj = new {
                    FxName           = Constants.AspNetMvcName,
                    UsedTime         = Constants.Unknown,
                    StatusCode       = statusCode,
                    ExceptionDetails = exception.Message
                };
                logger.LogError(exception, WebTemplateStandard.WebLog400, paramObj);
            }
            else
            {
                InternalLogger.WriteLine("Status code should not less than 400 when occurred error.");
            }
        }
Beispiel #13
0
        private void DispatchForAutomatic(int desiredItems = 1)
        {
            var readerTask = new Task(async() => {
                bool more = true;
                while (more)
                {
                    var result = await _automaticAsyncQueue.AcquireReadAsync(desiredItems, CancellationToken.None);
                    result.Visit(
                        succeeded => {
                        LogEvent logEvent = null;
                        if (succeeded is AcquireReadSucceeded <LogEvent> acquireReader)
                        {
                            logEvent = acquireReader.Items[0];
                            Dispatch(logEvent);
                        }

                        if (succeeded.ItemCount < 1)
                        {
                            more = false;
                        }

                        _automaticAsyncQueue.ReleaseRead(succeeded.ItemCount);

                        return(logEvent);
                    },
                        cancelled => {
                        InternalLogger.WriteLine("Dispatching task has been cancelled.");
                        return(null);
                    },
                        faulted => {
                        InternalLogger.WriteLine(
                            $@"Thrown an exception when dispatch log event from async queue:{Environment.NewLine}{faulted.Exception.ToUnwrappedString()}",
                            faulted.Exception);
                        return(null);
                    });
                }
            });

            readerTask.Start();
        }
Beispiel #14
0
        private static void UpdateTinyIoCContainer(TinyIoCContainer container)
        {
            var provider = NancyContainerSolo.ServiceProvider;

            container.Register <IServiceProvider>(provider, NancyContainerSolo.Name);
            var registrations = AllComponentsRegistrations;

            foreach (var registration in registrations)
            {
                var serviceType = registration.Many ? typeof(IEnumerable <>).MakeGenericType(registration.ServiceType) : registration.ServiceType;
                if (registration.Lifetime == ServiceLifetime.Singleton)
                {
                    if (registration.Many)
                    {
                        container.Register(serviceType, provider.GetServices(registration.ServiceType)).AsSingleton();
                    }
                    else
                    {
                        container.Register(serviceType, provider.GetService(registration.ServiceType)).AsSingleton();
                    }
                }
                else if (registration.Lifetime == ServiceLifetime.Scoped)
                {
                    InternalLogger.WriteLine("PreRequestSingleton do not supported by TinyIoC in NancyFX, but the Official's one does.");
                }
                else if (registration.Lifetime == ServiceLifetime.Transient)
                {
                    if (registration.Many)
                    {
                        container.Register(serviceType, provider.GetServices(registration.ServiceType)).AsMultiInstance();
                    }
                    else
                    {
                        container.Register(serviceType, provider.GetService(registration.ServiceType)).AsMultiInstance();
                    }
                }
            }
        }
        public static void OnEndHandle(HttpApplication application)
        {
            if (application == null)
            {
                return;
            }
            var ms = application.Context.Items[TimeKey] is DateTime stamp?DateTime.Now.Subtract(stamp).TotalMilliseconds : 0L;

            application.Context.Items.Remove(TimeKey);
            var logger    = StaticServiceResolver.Instance.GetLogger <HttpApplication>();
            var exception = application.Server.GetLastError();

            if (exception != null)
            {
                var statusCode = application.Response.StatusCode;
                if (statusCode >= 500)
                {
                    var realException = exception.Unwrap();
                    var paramObj      = new {
                        FxName               = Constants.AspNetMvcName,
                        UsedTime             = $"{ms} ms",
                        StatusCode           = statusCode,
                        ExceptionDetails     = exception.Message,
                        ExceptionType        = exception.GetType(),
                        ExceptionMessage     = exception.Message,
                        RealExceptionType    = realException.GetType(),
                        RealExceptionMessage = realException.Message,
                    };
                    logger.LogFatal(exception, WebTemplateStandard.WebLog500, paramObj);
                }
                else if (statusCode >= 400)
                {
                    var paramObj = new {
                        FxName           = Constants.AspNetMvcName,
                        UsedTime         = $"{ms} ms",
                        StatusCode       = statusCode,
                        ExceptionDetails = exception.Message
                    };
                    logger.LogError(exception, WebTemplateStandard.WebLog400, paramObj);
                }
                else
                {
                    InternalLogger.WriteLine("Status code should not less than 400 when occurred error.");
                }
            }
            else
            {
                var paramObj = new {
                    FxName           = Constants.AspNetMvcName,
                    UsedTime         = $"{ms} ms",
                    StatusCode       = application.Response.StatusCode,
                    ExceptionDetails = Constants.Null
                };
                if (ms > 1000)
                {
                    logger.LogWarning(WebTemplateStandard.LongNormal, paramObj);
                }
                else
                {
                    logger.LogDebug(WebTemplateStandard.Normal, paramObj);
                }
            }
        }