Пример #1
0
        protected override void ExecuteSubscriberProcess(BetTransactionMessage message, LogTrackerContext logtracker)
        {
            LogTrackerContext.Init(LogTrackerContextStorageTypeEnum.THREAD_DATASLOT, logtracker);
            _logger.Info(message.Id);

            //Console.WriteLine(message.Id);
            return;
        }
Пример #2
0
        protected override OutputMessageBase ExecuteSubscriberProcess(BetTransactionMessage message, LogTrackerContext logtracker)
        {
            LogTrackerContext.Init(LogTrackerContextStorageTypeEnum.THREAD_DATASLOT, logtracker);
            _logger.Info(message.Id);

            //throw new Exception("TEST");

            //Console.Write("start: {0}", message.Id);
            //Task.Delay(1000 * 10).Wait();
            //Console.Write("end: {0}", message.Id);

            return(new OutputMessageBase());
        }
Пример #3
0
        static void Main(string[] args)
        {
            LogTrackerLogger logger = new LogTrackerLogger(LogManager.GetCurrentClassLogger());
            Guid             guid1  = Guid.NewGuid();
            DateTime         dt1    = DateTime.UtcNow;

            Console.WriteLine(String.Format("Worker: request_id1: {0} | request_start_time_utc: {1}", guid1.ToString(), dt1));
            LogTrackerContext.Init(LogTrackerContextStorageTypeEnum.THREAD_DATASLOT, guid1.ToString(), dt1);
            MockZeus.Service.Mercury.TP.GBTP gb1 = new MockZeus.Service.Mercury.TP.GBTP();
            gb1.GetBalance();

            System.Threading.Thread.Sleep(1000);

            Guid     guid2 = Guid.NewGuid();
            DateTime dt2   = DateTime.UtcNow;

            Console.WriteLine(String.Format("Worker: request_id1: {0} | request_start_time_utc: {1}", guid2.ToString(), dt2));
            LogTrackerContext.Init(LogTrackerContextStorageTypeEnum.THREAD_DATASLOT, guid2.ToString(), dt2);
            MockZeus.Service.Mercury.TP.GBTP gb2 = new MockZeus.Service.Mercury.TP.GBTP();
            gb2.GetBalance();

            Console.ReadLine();
        }
Пример #4
0
        static void Main(string[] args)
        {
            //LogTrackerContext.Clean();

            //// Logger WITHOUT logConttext - To GrayLog
            //Console.WriteLine("Logger WITHOUT logConttext - To GrayLog");
            //LogTrackerLogger loggerWOCtxGL = new LogTrackerLogger(LogManager.GetLogger("ToGrayLog"));
            //loggerWOCtxGL.Info(new LogMessage() { Message = "This log has no context information from POC.Client" });
            //Console.ReadLine();

            //// Logger WITH explicit logConttext - To Gray Log
            //string request_id = Guid.NewGuid().ToString();
            //DateTime utcNow = DateTime.UtcNow;
            //LogTrackerContext lgc = LogTrackerContext.Init(LogTrackerContextStorageTypeEnum.NONE, request_id, utcNow);
            //Console.WriteLine("Logger WITH explicit logConttext - To Gray Log");
            //LogTrackerLogger loggerWTHCtxGL = new LogTrackerLogger(LogManager.GetLogger("ToGrayLog"), lgc);
            //loggerWTHCtxGL.Info(new LogMessage() { Message = "This log has context information from POC.Client" });
            //Console.ReadLine();
            //LogTrackerContext.Clean();


            //HttpClient client = new HttpClient();
            HttpClient client = new HttpClient(new LogTrackerHandler());

            client.BaseAddress = new Uri("http://localhost:31554/");
            Console.WriteLine(client.GetAsync("/api/values").Result);
            Console.WriteLine(client.GetAsync("/api/values/123").Result);

            // 測試Init錯誤參數
            LogTrackerContext wrong_request_id = LogTrackerContext.Init(LogTrackerContextStorageTypeEnum.NONE, "", DateTime.UtcNow);
            LogTrackerContext wrong_start_time = LogTrackerContext.Init(LogTrackerContextStorageTypeEnum.NONE, Guid.NewGuid().ToString(), DateTime.MinValue);
            // 以下測試需要將LogTrackerHandler中的request_id或start_time如上改成錯誤參數進行測試
            //HttpClient wrong_http_context = new HttpClient(new LogTrackerHandler());
            //client.BaseAddress = new Uri("http://localhost:31554/");
            //Console.WriteLine(wrong_http_context.GetAsync("/api/values").Result);
            //Console.WriteLine(wrong_http_context.GetAsync("/api/values/123").Result);
        }
Пример #5
0
        public void Test_ThreadDataSlotStorage_MultiThreads()
        {
            List <Task> tasks = new List <Task>();

            for (int i = 0; i < 10; i++)
            {
                tasks.Add(Task.Run(() =>
                {
                    //LogTrackerContext context = LogTrackerContext.Create("UNITTEST", LogTrackerContextStorageTypeEnum.THREAD_DATASLOT);
                    for (int y = 0; y < 10; y++)
                    {
                        string current_request_id     = Guid.NewGuid().ToString();
                        DateTime current_request_time = DateTime.UtcNow;

                        LogTrackerContext context = LogTrackerContext.Init(
                            LogTrackerContextStorageTypeEnum.THREAD_DATASLOT,
                            current_request_id,
                            current_request_time);

                        this.TestContext.WriteLine("TID: {0}, Request-ID: {1}, Request-Time: {2}", Thread.CurrentThread.ManagedThreadId, context.RequestId, context.RequestStartTimeUTC);

                        for (int x = 0; x < 10; x++)
                        {
                            Task.Delay(100).Wait();
                            Assert.AreEqual(
                                current_request_id,
                                LogTrackerContext.Current.RequestId);
                            Assert.AreEqual(
                                current_request_time,
                                LogTrackerContext.Current.RequestStartTimeUTC);
                        }
                    }
                }));
            }

            Task.WaitAll(tasks.ToArray());
        }
Пример #6
0
        private void StartProcessSubscribedMessage(SubscriberProcess process)
        {
            //this._stop = false;

            //Stopwatch totalWatch = new Stopwatch();
            //totalWatch.Start();
            _logger.Trace("WorkerThread({0}) - start running...", Thread.CurrentThread.ManagedThreadId);

            //using (var connection = MessageBusConfig.DefaultConnectionFactory.CreateConnection()) //this.connectionFactory.CreateConnection())
            using (var channel = this._connection.CreateModel())
            {
                channel.QueueDeclare(
                    queue: this.QueueName,
                    durable: true,
                    exclusive: false,
                    autoDelete: false,
                    arguments: null);

                BasicGetResult result = null;
                while (this._stop == false)
                {
                    try
                    {
                        result = channel.BasicGet(this.QueueName, false);
                        if (result == null)
                        {
                            Task.Delay(MessageBusConfig.DefaultPullWaitTime).Wait();
                            continue;
                        }
                        _logger.Trace("WorkerThread({0}) - receive message: {1}", Thread.CurrentThread.ManagedThreadId, result.BasicProperties.MessageId);
                    }
                    catch (Exception ex)
                    {
                        if (!_connection.IsOpen || channel.IsClosed)
                        {
                            _logger.Trace("WorkerThread({0}) message channel is closed. Reason: {1}", Thread.CurrentThread.ManagedThreadId,
                                          _connection.IsOpen ? channel.CloseReason : _connection.CloseReason);
                        }

                        this._stop       = true;
                        this._is_restart = true;
                        _logger.Warn(ex, "dequeue exception, restart subscriber...");

                        result = null;
                        break;
                    }

                    TOutputMessage response = null;

                    var body  = result.Body;
                    var props = result.BasicProperties;

                    bool current_reply = (string.IsNullOrEmpty(props.ReplyTo) == false);

                    var replyProps = channel.CreateBasicProperties();
                    replyProps.CorrelationId = props.CorrelationId;

                    LogTrackerContext logtracker = null;

                    if (props.Headers == null || props.Headers[LogTrackerContext._KEY_REQUEST_ID] == null)
                    {
                        // message without logtracker context info
                        logtracker = LogTrackerContext.Create(this.GetType().FullName, LogTrackerContextStorageTypeEnum.NONE);
                    }
                    else
                    {
                        string   req_id   = Encoding.UTF8.GetString((byte[])props.Headers[LogTrackerContext._KEY_REQUEST_ID]);
                        DateTime req_time = DateTime.Parse(Encoding.UTF8.GetString((byte[])props.Headers[LogTrackerContext._KEY_REQUEST_START_UTCTIME])).ToUniversalTime();

                        logtracker = LogTrackerContext.Init(
                            LogTrackerContextStorageTypeEnum.NONE,
                            req_id,
                            req_time);
                    }

                    try
                    {
                        TInputMessage request = JsonConvert.DeserializeObject <TInputMessage>(Encoding.Unicode.GetString(body));
                        _logger.Trace("WorkerThread({0}) - before processing message: {1}", Thread.CurrentThread.ManagedThreadId, props.MessageId);
                        response = process(request, logtracker);

                        _logger.Trace("WorkerThread({0}) - message was processed: {1}", Thread.CurrentThread.ManagedThreadId, props.MessageId);
                    }
                    catch (Exception e)
                    {
                        response = new TOutputMessage()
                        {
                            exception = e.ToString()
                        };
                        _logger.Warn(e, "WorkerThread({0}) - process message with exception: {1}, ex: {2}", Thread.CurrentThread.ManagedThreadId, props.MessageId, e);
                    }


                    try
                    {
                        if (current_reply)
                        {
                            byte[] responseBytes = null;//Encoding.UTF8.GetBytes(response);
                            if (response != null)
                            {
                                responseBytes = Encoding.Unicode.GetBytes(JsonConvert.SerializeObject(response));
                            }

                            channel.BasicPublish(
                                exchange: "",
                                routingKey: props.ReplyTo,
                                basicProperties: replyProps,
                                body: responseBytes);
                        }

                        channel.BasicAck(
                            deliveryTag: result.DeliveryTag,
                            multiple: false);
                    }
                    catch (Exception ex)
                    {
                        // connection fail while return message or ack.
                        // just shutdown and ignore it. non-return ack will be ignore, message will retry in next time
                        if (!_connection.IsOpen || channel.IsClosed)
                        {
                            _logger.Trace("WorkerThread({0}) message channel is closed. Reason: {1}", Thread.CurrentThread.ManagedThreadId,
                                          _connection.IsOpen ? channel.CloseReason : _connection.CloseReason);
                        }

                        this._stop       = true;
                        this._is_restart = true;
                        _logger.Warn(ex, "dequeue exception, restart subscriber...");

                        result = null;
                        break;
                    }
                }
            }

            _logger.Info("WorkerThread({0}) - {1} (restarting: {2}).", Thread.CurrentThread.ManagedThreadId, this.Status, this._is_restart); //this._stop?"stopped":"restarting");
        }