Exemplo n.º 1
0
        public void Setup()
        {
            _logger = SerilogHelper.CreateLogger(nameof(CmdGetCapabilitiesDescriptor_Test));
            var fac = SerilogHelper.GetLoggerFactory();

            _device = DeviceHelper.GetFirstSuitableDevice(fac);
        }
        private T ParseAcsResponse <T>(AcsRequest <T> request, HttpResponse httpResponse) where T : AcsResponse
        {
            SerilogHelper.LogInfo(request, httpResponse, SerilogHelper.ExecuteTime, SerilogHelper.StartTime);
            var format = httpResponse.ContentType;

            if (httpResponse.isSuccess())
            {
                return(ReadResponse(request, httpResponse, format));
            }

            try
            {
                var error = ReadError(request, httpResponse, format);
                if (null != error.ErrorCode)
                {
                    if (500 <= httpResponse.Status)
                    {
                        throw new ServerException(error.ErrorCode,
                                                  string.Format("{0}, the request url is {1}, the RequestId is {2}.", error.ErrorMessage,
                                                                httpResponse.Url ?? "empty", error.RequestId));
                    }

                    if (400 == httpResponse.Status && (error.ErrorCode.Equals("SignatureDoesNotMatch") ||
                                                       error.ErrorCode.Equals("IncompleteSignature")))
                    {
                        var errorMessage = error.ErrorMessage;
                        var re           = new Regex(@"string to sign is:", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                        var matches      = re.Match(errorMessage);

                        if (matches.Success)
                        {
                            var errorStringToSign = errorMessage.Substring(matches.Index + matches.Length);

                            if (request.StringToSign.Equals(errorStringToSign))
                            {
                                throw new ClientException("SDK.InvalidAccessKeySecret",
                                                          "Specified Access Key Secret is not valid.", error.RequestId);
                            }
                        }
                    }

                    throw new ClientException(error.ErrorCode, error.ErrorMessage, error.RequestId);
                }
            }
            catch (ServerException ex)
            {
                SerilogHelper.LogException(ex, ex.ErrorCode, ex.ErrorMessage);
                throw new ServerException(ex.ErrorCode, ex.ErrorMessage, ex.RequestId);
            }
            catch (ClientException ex)
            {
                SerilogHelper.LogException(ex, ex.ErrorCode, ex.ErrorMessage);
                throw new ClientException(ex.ErrorCode, ex.ErrorMessage, ex.RequestId);
            }

            var t = Activator.CreateInstance <T>();

            t.HttpResponse = httpResponse;
            return(t);
        }
        public void Setup()
        {
            _logger = SerilogHelper.CreateLogger(nameof(DataTransfer_Stability_Test));
            var fac = SerilogHelper.GetLoggerFactory();

            _device = DeviceHelper.GetFirstSuitableDevice(fac);
        }
Exemplo n.º 4
0
        private DataTransferResult RetrieveDataForPeriod(
            TimeSpan timeLimit,
            string testName)
        {
            var fac    = SerilogHelper.GetLoggerFactory();
            var logger = fac.CreateLogger(testName);

            using (var device = DeviceHelper.GetFirstSuitableDevice(fac))
            {
                var result = DataTransferTestHelper.RetrievePpgDataForPeriod(device, timeLimit, logger);

                var samplesCount = result.Packages.Sum(p => p.Samples.Length);

                _logger.LogInformation($"Time:     {result.ActualRuntime.TotalSeconds} seconds");
                _logger.LogInformation($"Packages: {result.Packages.Count}");
                _logger.LogInformation($"Samples:  {samplesCount}");

                var actualSamplingRate = samplesCount / result.ActualRuntime.TotalSeconds;

                actualSamplingRate.ShouldBe(400, 400 * 0.01);

                // Checkpoints
                return(result);
            }
        }
Exemplo n.º 5
0
        public void FeedLoQueueToDb()
        {
            while (true)
            {
                try
                {
                    if (!Program.feedLoQueue.Any())
                    {
                        continue;
                    }

                    using (var db = new dbEntities())
                    {
                        db.Database.Log = SerilogHelper.Verbose;
                        while (Program.feedLoQueue.TryDequeue(out var feed))
                        {
                            var typeName = feed.RouteKey.Split('.').Skip(3).FirstOrDefault();

                            RouteTheKey(typeName, feed, db);

                            if (Program.feedLoQueue.Count() > 10)
                            {
                                SerilogHelper.Error($"{Program.feedLoQueue.Count()} -> Queue count for feedLoQueue");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    SerilogHelper.Exception("FeedLoQueueToDb", $"Error when importing process!", ex);
                }
            }
        }
 public static IWebHostBuilder UseSerilogConfigured(this IWebHostBuilder webHostBuilder) =>
 webHostBuilder.UseSerilog((serviceProvider, _, baseConfig) =>
 {
     SerilogHelper.ConfigConsoleLogger(baseConfig)
     // NOTE: added an additional file logger with more exception and HTTP context details
     .WriteTo.Logger(config => SerilogHelper.ConfigRichFileLogger(config, serviceProvider));
 });
Exemplo n.º 7
0
        private static ServiceProvider BuildServiceProvider(string[] args)
        {
            var serviceCollection = new ServiceCollection()
                                    .AddSingleton <IDependencyGraphAnalyzer, DependencyGraphAnalyzer>()
                                    .AddSingleton <IDependencyGraphBuilder, DependencyGraphBuilder>()
                                    .AddSingleton <IDependencyGraphProcessor, PackageDowngradeScanner>()
                                    .AddSingleton <IDependencyGraphProcessor, PackageCreator>()
                                    .AddSingleton <IExecutionContextAccessor, ExecutionContextAccessor>()
                                    .AddSingleton <ICommandRunner, CommandRunner>()
                                    .AddSingleton <IDotNetPack, DotNetPack>()
                                    .AddSingleton <ICommandArgsExtractor>(new CommandArgsExtractor(args))
                                    .AddSingleton <Executor>();

            serviceCollection.AddSingleton <ILoggerFactory>(sp =>
            {
                var extractor = sp.GetRequiredService <ICommandArgsExtractor>();

                var level  = SerilogHelper.GetLevel(extractor.GetVerbosity());
                var logger = new LoggerConfiguration()
                             .WriteTo.Console(level, outputTemplate: "{NewLine}[{Level}] <{SourceContext:l}> {NewLine}{Message:lj}{NewLine}{Exception}{NewLine}")
                             .CreateLogger();

                return(new SerilogLoggerFactory(logger, dispose: true));
            });

            serviceCollection.AddTransient(typeof(ILogger <>), typeof(Logger <>));

            return(serviceCollection.BuildServiceProvider());
        }
Exemplo n.º 8
0
        private void BetSettlement(bet_settlement e, dbEntities db, string routeKey)
        {
            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                var sectionName = string.Empty;
                var spParams    = string.Empty;
                try
                {
                    var marketIdList  = string.Empty;
                    var specifierList = string.Empty;
                    var outcomeIdList = string.Empty;
                    var resultList    = string.Empty;
                    var certaintyList = string.Empty;
                    var productList   = string.Empty;

                    foreach (var market in e.outcomes)
                    {
                        var marketId  = market.id;
                        var specifier = market.specifiers?.Split('=').LastOrDefault()?.Trim();

                        foreach (var outcome in market.Items)
                        {
                            marketIdList  += marketId + ",";
                            specifierList += specifier + ",";
                            outcomeIdList += outcome.id.Split(':').LastOrDefault() + ",";
                            resultList    += outcome.result + ",";
                            certaintyList += e.certainty + ",";
                            productList   += e.product + ",";

                            marketId = 0;
                            if (!string.IsNullOrEmpty(specifier))
                            {
                                specifier = "*";
                            }
                        }
                    }

                    sectionName = "bet_settlement";
                    spParams    = "EXECUTE PROCEDURE BET_EVENTRESULTS_I_MULTI(";
                    spParams   += SourceId + ",";
                    spParams   += e.event_id.Split(':').Last() + ",";
                    spParams   += "'" + marketIdList.Substring(0).Trim() + "',";
                    spParams   += "'" + specifierList.Substring(0).Trim() + "',";
                    spParams   += "'" + outcomeIdList.Substring(0).Trim() + "',";
                    spParams   += "'" + resultList.Substring(0).Trim() + "',";
                    spParams   += "'" + certaintyList.Substring(0).Trim() + "',";
                    spParams   += "'" + productList.Substring(0).Trim() + "',";
                    spParams   += e.GeneratedAt + ")";
                    db.Database.ExecuteSqlCommand(spParams.Trim());

                    dbContextTransaction.Commit();
                    SerilogHelper.Information($"{routeKey} {UtcHelper.GetDifferenceFromTimestamp(e.timestamp) + "ms"}");
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();
                    SerilogHelper.Exception($"Unknown exception in {routeKey} SectionName:{sectionName} SQL:{spParams.Trim()}", ex);
                }
            }
        }
Exemplo n.º 9
0
        private void ProducerUpDown(ProducerModel e, dbEntities cnn, string routeKey)
        {
            var sectionName = string.Empty;

            using (var dbContextTransaction = cnn.Database.BeginTransaction())
            {
                try
                {
                    sectionName = "ProducerUpDown";
                    var spParams = "EXECUTE PROCEDURE BETDATA_ALIVE(";
                    spParams += SourceId + ",";
                    spParams += e.Id + ",";
                    spParams += "'" + e.Description + "',";
                    spParams += (e.IsAvailable ? 1 : 0) + ",";
                    spParams += (e.IsDisabled ? 1 : 0) + ",";
                    spParams += (e.IsProducerDown ? 1 : 0) + ")";
                    cnn.Database.ExecuteSqlCommand(spParams.Trim());

                    dbContextTransaction.Commit();

                    SerilogHelper.Information(string.Format("ProducerUpDown ID:{0} Description:{1} IsAvailable:{2} IsDisabled:{3} IsProducerDown:{4}", e.Id, e.Description, e.IsAvailable, e.IsDisabled, e.IsProducerDown));
                    SerilogHelper.Information(string.Format("{0}", routeKey));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();
                    SerilogHelper.Exception(string.Format("Unknown exception in {0}", sectionName), ex);
                }
            }
        }
Exemplo n.º 10
0
        public async Task <IActionResult> GetService()
        {
            SerilogHelper.GetInstance(_config).Information("hello");
            await Async1("tien", "nam");

            return(Ok(_aService.GetName()));
        }
Exemplo n.º 11
0
        private static void TeamMeta(List <TeamMeta> e, long sportId, long tournamentId, dbEntities cnn)
        {
            foreach (var team in e)
            {
                if (team == null)
                {
                    continue;
                }

                /*var spParams = "EXECUTE PROCEDURE BET_TEAMS_I(";
                *  spParams += sourceId + ",";
                *  spParams += sportId + ",";
                *  spParams += tournamentId + ",";
                *  spParams += team.TeamId + ",";
                *  spParams += 1 + ",";
                *  spParams += 0 + ")";
                *  cnn.Database.ExecuteSqlCommand(spParams.Trim());*/

                var spParams = "EXECUTE PROCEDURE BET_TRANSLATIONSIMPORT(";
                spParams += "'en',";
                spParams += team.TeamId + ",";
                spParams += 7 + ",";
                spParams += "'" + team.DefaultName + "',";
                spParams += tournamentId + ")";
                cnn.Database.ExecuteSqlCommand(spParams.Trim());
                SerilogHelper.Debug("Translation team ");
            }

            SerilogHelper.Debug("META team");
        }
Exemplo n.º 12
0
 private void button2_Click(object sender, EventArgs e)
 {
     //发送数据
     foreach (var item in Overall.ListIP)
     {
         try
         {
             var one = Overall.lsocket.FirstOrDefault(x => x.Key == item.IpAddressInfo).Value;
             if (one != null)
             {
                 byte[] buff = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
                 Overall.OverAllForm.server.SendMessage(one, buff);
                 SerilogHelper.Log4Debug(item.IpAddressInfo + "Sync Time...", Outputoption.Info);
             }
             else
             {
                 SerilogHelper.Log4Debug(item.IpAddressInfo + "Build Socket Faild!", Outputoption.Error);
             }
         }
         catch (Exception ex)
         {
             SerilogHelper.Log4Debug(item.IpAddressInfo + " happened one Error . Msg: " + ex.Message, Outputoption.Error);
         }
     }
 }
        public virtual AlibabaCloudCredentials GetCredentials()
        {
            try
            {
                if (credentials == null)
                {
                    credentials = fetcher.Fetch(maxRetryTimes);
                }

                if (credentials.IsExpired())
                {
                    throw new ClientException("SDK.SessionTokenExpired", "Current session token has expired.");
                }

                if (!credentials.WillSoonExpire() || !credentials.ShouldRefresh())
                {
                    return(credentials);
                }

                credentials = fetcher.Fetch();
                return(credentials);
            }
            catch (ClientException ex)
            {
                if (ex.ErrorCode.Equals("SDK.SessionTokenExpired") && ex.ErrorMessage.Equals("Current session token has expired."))
                {
                    SerilogHelper.LogException(ex, ex.ErrorCode, ex.ErrorMessage);
                    throw new ClientException(ex.ErrorCode, ex.ErrorMessage);
                }

                // Use the current expiring session token and wait for next round
                credentials.SetLastFailedRefreshTime();
            }
            return(credentials);
        }
Exemplo n.º 14
0
 private void StartServerBtn_Click(object sender, EventArgs e)
 {
     if ((TheServerStartEnum)this.StartServerBtn.Tag == TheServerStartEnum.Stop)
     {
         #region 启动服务器
         try
         {
             MethodStartServer();
         }
         catch (Exception ex)
         {
             SerilogHelper.FileLog(Outputoption.Error, ex.Message);
         }
         #endregion
         this.StartServerBtn.BackColor = System.Drawing.Color.LightGreen;
         this.StartServerBtn.Text      = "Stop";
         this.StartServerBtn.Tag       = TheServerStartEnum.Start;
     }
     else
     {
         #region 停止服务器
         try
         {
             MethodStopServer();
         }
         catch (Exception ex)
         {
             SerilogHelper.FileLog(Outputoption.Error, ex.Message);
         }
         #endregion
         this.StartServerBtn.BackColor = System.Drawing.Color.Red;
         this.StartServerBtn.Text      = "Start";
         this.StartServerBtn.Tag       = TheServerStartEnum.Stop;
     }
 }
        public void Init_Retry_1000()
        {
            var fac         = SerilogHelper.GetLoggerFactory();
            var fwRevision  = "";
            var fwBuildDate = "";

            for (int i = 0; i < 1000; ++i)
            {
                try
                {
                    using (var device = DeviceHelper.GetFirstSuitableDevice(fac))
                    {
                        var caps         = device.GetCapabilities();
                        var serialNumber = caps.SerialNumber;

                        if (string.IsNullOrEmpty(fwRevision))
                        {
                            fwRevision = caps.RevisionInfo;
                        }
                        if (string.IsNullOrEmpty(fwBuildDate))
                        {
                            fwBuildDate = caps.FirmwareBuildDate;
                        }
                    }
                }
                catch
                {
                    _logger.LogInformation($"Failed after {i} successful attempts");
                    _logger.LogInformation($"Last FW revision was:   {fwRevision}");
                    _logger.LogInformation($"Last FW build date was: {fwBuildDate}");
                    throw;
                }
            }
        }
Exemplo n.º 16
0
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                          .AddEnvironmentVariables();

            Configuration = configuration;
            if (env.IsDevelopment())
            {
                // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
                // builder.AddApplicationInsightsSettings(developerMode: true);
                builder.AddUserSecrets <Startup>();
                useTypeFullNames        = false;
                returnOnlyKeyIfNotFound = false;

                _createNewRecordWhenLocalisedStringDoesNotExist = true;
            }
            else
            {
                // builder.build() is required to complete adding of AppSettings.json to the Configuration
                Configuration = builder.Build();
                _createNewRecordWhenLocalisedStringDoesNotExist = string.IsNullOrWhiteSpace(Configuration["Localization:CreateNewRecordWhenLocalisedStringDoesNotExist"]) ?
                                                                  false : bool.Parse((Configuration["Localization:CreateNewRecordWhenLocalisedStringDoesNotExist"]));
            }

            Configuration = builder.Build();
            _hostingEnv   = env; // Inject hosting environment

            /// Setup Serilog, logging of site in file
            SerilogHelper.SetupSerilog();
        }
Exemplo n.º 17
0
        public static void ReceiveMeta()
        {
            var rbService = new RabbitMQService();
            var conn      = rbService.GetRabbitMQConnection();
            var meta      = conn.CreateModel();

            meta.ExchangeDeclare("Metas", durable: true, type: ExchangeType.Fanout);
            var queueName = meta.QueueDeclare().QueueName;

            meta.QueueBind(queue: queueName, exchange: "Metas", routingKey: "UOFMetas");
            meta.BasicQos(prefetchSize: 0, prefetchCount: 1, false);
            var metaConsumer = new EventingBasicConsumer(meta);

            meta.BasicConsume(queueName, false, metaConsumer);
            SerilogHelper.Information($"Connected Metas {queueName}");

            metaConsumer.Received += (model, ea) =>
            {
                var body  = ea.Body;
                var data  = Encoding.UTF8.GetString(body);
                var _data = UtcHelper.Deserialize <Meta>(data);
                Program.metaMainQueue.Enqueue(_data);
                meta.BasicAck(ea.DeliveryTag, multiple: false);
            };
        }
Exemplo n.º 18
0
        public void OutputLogInfoTestInValid()
        {
            string format = "{code}|{pid}|{start_time}";
            var    logger = new Logger(loggerPath: EnvironmentUtil.GetHomePath() + EnvironmentUtil.GetOSSlash() + "log.txt", template: format);

            SerilogHelper.SetLogger(logger);

            var request = new AssumeRoleRequest
            {
                Url = "https://www.alibabacloud.com"
            };
            var    response    = new HttpResponse();
            long   executeTime = 100;
            string startTime   = DateTime.Now.ToString();

            Assert.Throws <ClientException>(() =>
            {
                SerilogHelper.LogInfo(request, null, executeTime, startTime);
            });

            SerilogHelper.CloseLogger();
            Assert.False(SerilogHelper.EnableLogger);

            SerilogHelper.LogInfo(request, null, 100, "100");
        }
Exemplo n.º 19
0
        private void BetStop(bet_stop e, dbEntities cnn, string routeKey)
        {
            using (var dbContextTransaction = cnn.Database.BeginTransaction())
            {
                var sectionName = string.Empty;
                var spParams    = string.Empty;
                try
                {
                    sectionName = "bet_stop";
                    spParams    = "EXECUTE PROCEDURE BET_EVENTBETSTOP_I(";
                    spParams   += SourceId + ",";
                    spParams   += e.event_id.Split(':').Last() + ",";
                    spParams   += e.product + ",";
                    spParams   += "'" + e.groups?.Trim() + "',";
                    spParams   += e.market_status + ",";
                    spParams   += e.GeneratedAt + ")";
                    cnn.Database.ExecuteSqlCommand(spParams.Trim());

                    dbContextTransaction.Commit();

                    SerilogHelper.Information($"{routeKey} {UtcHelper.GetDifferenceFromTimestamp(e.timestamp) + "ms"}");
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();
                    SerilogHelper.Exception($"Unknown exception in {routeKey} SectionName:{sectionName} SQL:{spParams.Trim()}", ex);
                }
            }
        }
Exemplo n.º 20
0
        public void Setup()
        {
            _logger = SerilogHelper.CreateLogger(nameof(X20Device_Test));
            var fac = SerilogHelper.GetLoggerFactory();

            _device = DeviceHelper.GetFirstSuitableDevice(fac);
        }
Exemplo n.º 21
0
        private void FixtureChange(fixture_change e, dbEntities db, string routeKey)
        {
            var sectionName = string.Empty;

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    sectionName = "fixture_change";
                    var spParams = "EXECUTE PROCEDURE BET_EVENTFIXTURECHANGE_I(";
                    spParams += SourceId + ",";
                    spParams += e.event_id.Split(':').Last() + ",";
                    spParams += e.product + ",";
                    spParams += e.change_type + ",";
                    spParams += e.GeneratedAt + ")";
                    db.Database.ExecuteSqlCommand(spParams.Trim());

                    dbContextTransaction.Commit();
                    SerilogHelper.Information(string.Format("{0} {1}", routeKey, UtcHelper.GetDifferenceFromTimestamp(e.timestamp) + "ms"));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();
                    SerilogHelper.Exception(string.Format("Unknown exception in {0} {1} {2}", routeKey, sectionName, e.event_id), ex);
                }
            }
        }
Exemplo n.º 22
0
        private void BetCancel(bet_cancel e, dbEntities db, string routeKey)
        {
            var sectionName = string.Empty;

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    sectionName = "bet_cancel";
                    foreach (var market in e.market)
                    {
                        var specifier = market.specifiers?.Split('=').LastOrDefault().Trim();
                        var spParams  = "EXECUTE PROCEDURE BET_EVENTBETCANCEL_I(";
                        spParams += SourceId + ",";
                        spParams += e.event_id.Split(':').Last() + ",";
                        spParams += e.product + ",";
                        spParams += e.start_time + ",";
                        spParams += e.end_time + ",";
                        spParams += market.id + ",";
                        spParams += "'" + specifier + "',";
                        spParams += market.void_reason + ",";
                        spParams += e.GeneratedAt + ")";
                        db.Database.ExecuteSqlCommand(spParams.Trim());
                    }
                    dbContextTransaction.Commit();
                    SerilogHelper.Information(string.Format("{0} {1}", routeKey, UtcHelper.GetDifferenceFromTimestamp(e.timestamp) + "ms"));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();
                    SerilogHelper.Exception(string.Format("Unknown exception in {0} {1} {2}", routeKey, sectionName, e.event_id), ex);
                }
            }
        }
Exemplo n.º 23
0
        public async System.Threading.Tasks.Task UpdateLogger_ForInvalidJson_IsAbleToReload()
        {
            Log.Logger = new SilentLogger();
            Assert.IsFalse(Log.Logger is Logger);

            CopyFile(serilogConfig, validJson);
            IConfigurationBuilder configurationBuilder;

            SerilogHelper.CreateLogger(configure =>
            {
                configurationBuilder = configure.AddJsonFile(JsonFilePath(serilogConfig), optional: false, reloadOnChange: true);
            });
            Assert.IsTrue(Log.Logger is Logger);

            Log.Logger = new SilentLogger();
            Assert.IsFalse(Log.Logger is Logger);

            // Verify reload does not occur for invalid json
            CopyFile(serilogConfig, invalidJson);
            await WaitForReloadEvent();

            Assert.IsFalse(Log.Logger is Logger);

            // Verify reload token is still active
            CopyFile(serilogConfig, validJson);
            await WaitForReloadEvent();

            Assert.IsTrue(Log.Logger is Logger);
        }
Exemplo n.º 24
0
        /// <summary>
        ///     Fail
        /// </summary>
        /// <param name="error"></param>
        /// <returns></returns>
        protected Task <TResponse <T> > Fail <T>(Error error)
        {
            var res = new TResponse <T>(default(T), false, error.Message, error.ErrorCode);

            SerilogHelper.GetLogger()
            ?.Error(res.ToJson());
            return(Task.FromResult(res));
        }
Exemplo n.º 25
0
        public static async Task Main(string[] args)
        {
            SerilogHelper.SetupSerilog();

            await CreateHostBuilder(args)
            .Build()
            .RunAsync();
        }
Exemplo n.º 26
0
        protected Task <TResponse <T> > NotFound <T>(Error error,
                                                     params string[] message)
        {
            var res = new TResponse <T>(default(T), true, string.Format(error.ErrorCode, message), error.ErrorCode);

            SerilogHelper.GetLogger()
            ?.Error(res.ToJson());
            return(Task.FromResult(res));
        }
Exemplo n.º 27
0
        public void Setup()
        {
            _logger = SerilogHelper.CreateLogger(nameof(DataTransfer_Test));

            var fac = SerilogHelper.GetLoggerFactory();

            _device = DeviceHelper.GetFirstSuitableDevice(fac);
            var usePpgResponse = _device.UsePpgWaveform();
        }
 public static IApplicationBuilder UseRequestLogging(this IApplicationBuilder builder, bool excludeHealthChecks = true)
 {
     return(builder
            .UseSerilogRequestLogging(options =>
     {
         options.EnrichDiagnosticContext = SerilogHelper.EnrichFromRequest;
         if (excludeHealthChecks)
         {
             options.GetLevel = SerilogHelper.GetLevel(LogEventLevel.Verbose, "Health checks");
         }
     }));
 }
Exemplo n.º 29
0
 private void MethodStopServer()
 {
     if (server != null)
     {
         Overall.lsocket.Clear();
         server.Stop();
         server.Dispose();
         //this.GetMsgList.Items.Add("The Server is Close...");
         SerilogHelper.Log4Debug("The server is Close ....", Outputoption.Info);
         this.SettingBtn.Enabled = true;
     }
     Overall.ListIP.Clear();
 }
Exemplo n.º 30
0
        public void MetaMainQueueToDb()
        {
            var sectionName = "MetaMainQueueToDb";

            while (true)
            {
                try
                {
                    if (!Program.metaMainQueue.Any())
                    {
                        continue;
                    }

                    using (dbEntities db = new dbEntities())
                    {
                        db.Database.Log = SerilogHelper.Verbose;
                        while (Program.metaMainQueue.TryDequeue(out Meta meta))
                        {
                            using (var dbContextTransaction = db.Database.BeginTransaction())
                            {
                                try
                                {
                                    EventMeta(meta.Sport.Category.Tournament.Match, meta.Markets, db);
                                    TeamMeta(meta.Teams, meta.Sport.SportId,
                                             meta.Sport.Category.Tournament.TournamentId, db);

                                    dbContextTransaction.Commit();
                                }
                                catch (Exception ex)
                                {
                                    dbContextTransaction.Rollback();
                                    SerilogHelper.Exception(
                                        string.Format("Unknown exception in {0} {1}", sectionName,
                                                      meta.Sport.Category.Tournament.Match.EventId), ex);
                                }
                            }

                            if (Program.metaMainQueue.Count() > 10)
                            {
                                SerilogHelper.Error($"{Program.metaMainQueue.Count()} -> Queue count for metaMainQueue");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    SerilogHelper.Exception("metaToDb", $"Error when importing process!", ex);
                }
            }
        }