示例#1
0
文件: Fx.cs 项目: wwwK/Dnc.Core
        public static void ConfigureBuild(this FrameworkConstruction construction,
                                          Func <FrameworkConstruction, IServiceProvider> serviceProviderFactory = null,
                                          bool logStarted = true)
        {
            try
            {
                SrvRegisteredEvent?.Invoke(construction.Services);

                if (construction.Services == null)
                {
                    throw new Exception("ServiceCollection is null.");
                }

                ServiceProvider = serviceProviderFactory.Invoke(construction);

                if (logStarted)
                {
                    var logger = ServiceProvider.GetService <ILogger>();
                    var env    = ServiceProvider.GetService <IFrameworkEnvironment>();

                    logger.LogCritical($"Dnc core  started in {env.Environment}...");
                }
            }
            catch (Exception ex)
            {
                ExceptionThrownEvent?.Invoke(ex);
            }
        }
示例#2
0
        public void DispatcherTest()
        {
            using (var eventSender = new EventPublisher(_config))
                using (FoutLoggingContext context = new FoutLoggingContext(_options))
                    using (CustomExceptionRepository repo = new CustomExceptionRepository(context))
                        using (FoutLoggingDispatcher dispatcher = new FoutLoggingDispatcher(_config, repo))
                        {
                            var myException = new ExceptionThrownEvent()
                            {
                                ExceptionType = typeof(ArgumentException),
                                GUID          = Guid.NewGuid().ToString(),
                                Message       = "Dit is een TestException",
                                TimeStamp     = DateTime.Now,
                                RoutingKey    = "jomaya.exception.Test"
                            };

                            eventSender.Publish(myException);

                            Thread.Sleep(3000);

                            Assert.IsTrue(context.Exceptions.Count(c => c.ExceptionType == typeof(ArgumentException).ToString()) > 0);

                            var result = context.Exceptions.First(c => c.ExceptionType == typeof(ArgumentException).ToString());

                            Assert.AreEqual("Dit is een TestException", result.Message);
                        }
        }
示例#3
0
 /// <summary>
 /// Удаляет лог-файл с накопителя информации либо из памяти
 /// </summary>
 /// <exception cref="System.ArgumentException"/>
 /// <exception cref="System.ArgumentNullException"/>
 /// <exception cref="System.IO.DirectoryNotFoundException"/>
 /// <exception cref="System.IO.IOException"/>
 /// <exception cref="System.IO.PathTooLongException"/>
 /// <exception cref="System.UnauthorizedAccessException"/>
 /// <exception cref="System.NotSupportedException"/>
 public void Delete()
 {
     try {
         if (this._logType == LogTypes.Text)
         {
             if (String.IsNullOrEmpty(this._logPath))
             {
                 throw new ArgumentNullException("Не задан путь расположения лог-файла");
             }
             if (File.Exists(this._logPath))
             {
                 lock (_fileLock) {
                     File.Delete(this._logPath);
                 }
             }
         }
         else
         {
             this._memory.Clear();
         }
     }
     catch (Exception ex) {
         ExceptionThrownEvent?.Invoke(ex);
         if (_enableThrows)
         {
             throw;
         }
     }
 }
示例#4
0
        /// <summary>
        /// Сохраняет лог-файл из памяти на накопитель информации
        /// </summary>
        /// <param name="encoding">Кодировка записываемого текста</param>
        /// <exception cref="System.InvalidOperationException"/>
        /// <exception cref="System.ArgumentNullException"/>
        public void SaveFromMemory(Encoding encoding)
        {
            try {
                if (this._logType != LogTypes.Memory)
                {
                    throw new InvalidOperationException("Для выполнения данной операции лог-файл должен иметь тип LogTypes.Memory");
                }
                if (String.IsNullOrEmpty(this._logPath))
                {
                    throw new ArgumentNullException("Не задан путь для сохранения лог-файла");
                }

                lock (_fileLock) {
                    File.AppendAllText(this._logPath, this._memory.ToString(), encoding);
                }
                _CheckAutoCompress();
            }
            catch (Exception ex) {
                ExceptionThrownEvent?.Invoke(ex);
                if (_enableThrows)
                {
                    throw;
                }
            }
        }
示例#5
0
        /// <summary>
        /// Записывает строку с указанным текстом в лог-файл
        /// </summary>
        /// <param name="text">Текст для записи</param>
        /// <param name="encoding">Кодировка записываемого текста</param>
        /// <param name="msgType">Тип выводимого сообщения</param>
        /// <exception cref="System.FormatException"/>
        /// <exception cref="System.ArgumentException"/>
        /// <exception cref="System.ArgumentNullException"/>
        /// <exception cref="System.IO.PathTooLongException"/>
        /// <exception cref="System.IO.DirectoryNotFoundException"/>
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="System.UnauthorizedAccessException"/>
        /// <exception cref="System.IO.FileNotFoundException"/>
        /// <exception cref="System.NotSupportedException"/>
        /// <exception cref="System.Security.SecurityException"/>
        public void Write(string text, Encoding encoding, MessageType msgType = MessageType.None)
        {
            try {
                string date   = (this._insertDateTime) ? "[" + DateTime.Now.ToString(this._dateFormat) + "]" : "";
                string result = String.Format("{0} {1} {2}{3}", date, _StringFromMessageType(msgType), text, "\r\n");

                if (this._logType == LogTypes.Text)
                {
                    lock (_fileLock) {
                        File.AppendAllText(this._logPath, result, encoding);
                    }
                    _CheckAutoCompress();
                }
                else if (this._logType == LogTypes.Memory)
                {
                    this._memory.Append(result);
                }
            }
            catch (Exception ex) {
                ExceptionThrownEvent?.Invoke(ex);
                if (_enableThrows)
                {
                    throw;
                }
            }
        }
        public void OnExceptionThrownEvent(ExceptionThrownEvent exceptionThrownEvent)
        {
            var customException = new CustomException()
            {
                ExceptionType = exceptionThrownEvent.ExceptionType.ToString(),
                Message       = exceptionThrownEvent.Message,
                StackTrace    = exceptionThrownEvent.StackTrace
            };

            _repo.Insert(customException);
        }
示例#7
0
 internal void _CheckAutoCompress()
 {
     try {
         if (AutoCompress && LogLength >= MaxLogLength)
         {
             Compress(this.LogPath, string.Format("{0}_{1}.gz", this.LogPath, DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss")));
             Delete();
         }
     }
     catch (Exception ex) {
         ExceptionThrownEvent?.Invoke(ex);
         if (_enableThrows)
         {
             throw;
         }
     }
 }
示例#8
0
文件: Fx.cs 项目: wwwK/Dnc.Core
        public static FrameworkConstruction Construct <T>()
            where T : FrameworkConstruction, new()
        {
            try
            {
                Construction = new T();

                Construction.Configure()
                .UseDefaultLogger();
                Construction.Services.AddMemoryCache();
                Construction.Services.AddAssemblyPluginTypes();
            }
            catch (Exception ex)
            {
                ExceptionThrownEvent?.Invoke(ex);
            }

            return(Construction);
        }
        public static void PublishException(Exception e, bool inDockerContainer = true)
        {
            string eventBusHost;
            int    eventBusPort;

            if (inDockerContainer)
            {
                eventBusHost = "rabbitmq";
                eventBusPort = 5672;
            }
            else
            {
                eventBusHost = "localhost";
                eventBusPort = 5673;
            }

            var config = new EventBusConfig()
            {
                Host         = eventBusHost,
                Port         = eventBusPort,
                QueueName    = "jomaya.exception.publisher",
                ExchangeName = "my-bus"
            };

            var myEvent = new ExceptionThrownEvent()
            {
                ExceptionType = e.GetType(),
                GUID          = Guid.NewGuid().ToString(),
                Message       = e.Message,
                RoutingKey    = "jomaya.exception.exceptionthrownevent",
                StackTrace    = e.StackTrace,
                TimeStamp     = DateTime.Now
            };

            using (var publisher = new EventPublisher(config))
            {
                publisher.Publish(myEvent);
            }
        }