public async Task StartServer() { log.Debug(Resources.LoggingMessages.server_starting); server = await LanguageServer.From(options => options .WithInput(Console.OpenStandardInput()) .WithOutput(Console.OpenStandardOutput()) .ConfigureLogging(x => x .AddSerilog(log) .AddLanguageServer() ) .WithServices(ConfigureServices) .WithHandler <TextDocumentSyncTaskHandler>() .WithHandler <DidChangeWatchedFilesHandler>() .WithHandler <CompletionTaskHandler>() .WithHandler <CompileHandler>() .WithHandler <CounterExampleHandler>() .WithHandler <CodeLensTaskHandler>() .WithHandler <DefinitionTaskHandler>() .WithHandler <RenameTaskHandler>() .WithHandler <HoverTaskHandler>() .WithHandler <ShutdownHandler>() ); ExecutePostLaunchTasks(); await RedirectStreamUntilServerExits(); log.Debug(Resources.LoggingMessages.server_closed); }
public async Task Start() { _logger.Debug("Starting PizzaCore"); await CreateConnection(); _logger.Information("PizzaCore finished starting up."); }
public void Stop() { Log.Debug("Stop command received, checking queue..."); // Wait until queue is empty cts.Cancel(); Log.Debug("Stopped working."); }
public static void Main() { Logger = new LoggerConfiguration() .Enrich.WithMachineName() .Enrich.FromLogContext() .WriteTo.LiterateConsole() .WriteTo.Async(a => a .RollingFile( pathFormat: "data/logs/log-{Date}.txt", buffered: true )) .CreateLogger(); try { var sep = Path.DirectorySeparatorChar; DirectoryInfo info = new DirectoryInfo(Directory.GetCurrentDirectory()); try { while (new FileInfo($@"{info.FullName}{sep}ClientApp{sep}boot-client.tsx").Exists == false) { info = info.Parent; } ; } catch { info = new DirectoryInfo(Directory.GetCurrentDirectory()); } Logger.Information($@"Application current directory set to {info.FullName}"); Directory.SetCurrentDirectory(info.FullName); Logger.Debug("Building web server configuration"); var host = new WebHostBuilder() .UseKestrel(options => { options.AddServerHeader = false; options.ListenAnyIP(443, listen => { listen.UseHttps("data/certs/certfile.pfx", ""); }); }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>() .UseSerilog(Logger) .Build(); Logger.Debug("Starting web server"); host.Run(); } catch (Exception e) { Logger.Fatal("Unknown exception in web server caused failure", e); } finally { Log.CloseAndFlush(); } }
/// <inheritdoc /> public void Debug <T1>(string template, T1 parameter1) { if (!IsEnabled(LogLevel.Debug)) { return; } _target.Debug(template, parameter1); }
private static async Task StartSilo(string[] args) { _log.Debug("Building silo host"); _silo = BuildSilo(args, ConfigureServices); _log.Information("Starting orleans silo host"); await _silo.StartAsync(); _log.Information("Orleans silo host started"); }
public void Debug(string message, Exception exception = null) { if (exception != null) { _log.Debug(exception, message); } else { _log.Debug(message); } }
private void CreateBookStore(ApplicationDbContext db, BookStoreInitializedEvent @event) { _log.Debug($"Creating book store entity {@event.Id}"); var bookStore = new Database.Entities.BookStore { Id = @event.Id, Name = @event.Name, Address = JsonConvert.SerializeObject(@event.Address) }; db.BookStores.Add(bookStore); }
public void OnEnable() { logger.Debug("Creating scheduler host object"); schedulerHostObject = new GameObject(ownMeta.Name + " Dispatcher Scheduler Host"); UnityObject.DontDestroyOnLoad(schedulerHostObject); schedulerHost = schedulerHostObject.AddComponent <CoroHost>(); UnityObject.DontDestroyOnLoad(schedulerHost); // start the scheduler schedulerHost.StartCoroutine(scheduler.Coroutine()); logger.Debug("Plugin enabled"); }
// GetList public List <T> GetList <T>(T model) { try { var list = connection.Query <T>(repoString.SelectString(model), model).ToList(); logger.Debug(this.LogMessage(repoString.SelectString(model), JsonConvert.SerializeObject(model))); return(list); } catch (Exception ex) { logger.Error(this.LogMessage(repoString.SelectString(model), JsonConvert.SerializeObject(model))); throw ex; } }
private Task On(RawEvent rawEvent, Position?position, DateTime eventCreationTime) { var @event = _deserializer.Deserialize(rawEvent); _log.Debug("Projecting event {event}", rawEvent.Body.ToString()); try { // return Measure(() =>// Should be moved to a messenger decorator // { var envelopedEvent = new EventEnvelope( new MessageChainInfo(@event.Id.ToString() , @event.Metadata.CorrelationId , @event.Metadata.CausationId) , @event.Body); _messenger.Dispatch(envelopedEvent); return(_checkpointStore.StoreCheckpoint(position)); // }, rawEvent.EventType // , eventCreationTime // , _subscriptionName); } catch (Exception exception) { _log.Error(exception , "Error occured when projecting the event {event} from {subscriptionName}" , @event , _subscriptionName); throw; } }
/// <inheritdoc /> public Task LogMessage(LogMessage message) { switch (message.Severity) { case LogSeverity.Error: case LogSeverity.Critical: _logger.Fatal($"{message.Source}: {message.Message} {message.Exception}"); break; case LogSeverity.Warning: _logger.Warning($"{message.Source}: {message.Message} {message.Exception}"); break; case LogSeverity.Info: _logger.Information($"{message.Source}: {message.Message} {message.Exception}"); break; case LogSeverity.Verbose: _logger.Verbose($"{message.Source}: {message.Message} {message.Exception}"); break; case LogSeverity.Debug: _logger.Debug($"{message.Source}: {message.Message} {message.Exception}"); break; default: throw new ArgumentOutOfRangeException(); } return(Task.CompletedTask); }
public Task AppendEvents(string streamName , long version , UntypedEventEnvelope[] events) { foreach (var @event in events) { _log.Debug($"Persisting event {@event.Body}"); } if (events == null || !events.Any()) { return(Task.CompletedTask); } var preparedEvents = events .Select(ConvertEventEnvelopeToEventData).ToArray(); return(_connection.AppendToStreamAsync( streamName, version, preparedEvents )); // return _connection.AppendEvents( // streamName, version, events // ); }
IDocumentStore ConfigureRaven() { var store = new DocumentStore { Urls = new[] { Configuration["RavenDb:Url"] }, Database = Configuration["RavenDb:Database"] }; if (Environment.IsDevelopment()) { store.OnBeforeQuery += (_, args) => args.QueryCustomization .WaitForNonStaleResults() .AfterQueryExecuted(result => { Log.ForContext("SourceContext", "Raven").Debug("{index} took {duration}", result.IndexName, result.DurationInMs); }); } try { store.Initialize(); Log.Information("Connection to {url} document store established.", store.Urls[0]); } catch (Exception ex) { throw new ApplicationException( $"Failed to establish connection to \"{store.Urls[0]}\" document store!" + $"Please check if https is properly configured in order to use the certificate.", ex); } try { var record = store.Maintenance.Server.Send(new GetDatabaseRecordOperation(store.Database)); if (record == null) { store.Maintenance.Server .Send(new CreateDatabaseOperation(new DatabaseRecord(store.Database))); Log.Debug("{database} document store database created.", store.Database); } } catch (Exception ex) { throw new ApplicationException( $"Failed to ensure that \"{store.Database}\" document store database exists!", ex); } try { IndexCreation.CreateIndexes(Assembly.GetExecutingAssembly(), store); Log.Information("{database} document store database indexes created or updated.", store.Database); } catch (Exception ex) { throw new ApplicationException($"Failed to create or update \"{store.Database}\" document store database indexes!", ex); } return(store); }
async Task EventAppeared( EventStoreCatchUpSubscription _, ResolvedEvent resolvedEvent ) { if (resolvedEvent.Event.EventType.StartsWith("$")) { return; } var @event = resolvedEvent.Deserialze(); _log.Debug("Projecting event {event}", @event.ToString()); try { await Task.WhenAll(_eventHandlers.Select(x => x(@event))); await _checkpointStore.StoreCheckpoint(resolvedEvent.OriginalPosition); } catch (Exception e) { _log.Error( e, "Error occured when projecting the event {event}", @event ); throw; } }
public async Task <AlprResult> CallAlprService(string base64Image, Guid uniqueId) { using (var client = new HttpClient()) { var obj = new { Base64Image = base64Image }; var content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json"); var response = await client.PostAsync(_settings.AlprUrl, content); _logger.Debug($"Request Id: {uniqueId} Response from ALPR - {response.StatusCode} , {response.ReasonPhrase}"); if (!response.IsSuccessStatusCode) { return(null); } var buffer = await response.Content.ReadAsByteArrayAsync(); var byteArray = buffer.ToArray(); var responseString = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length); var result = JsonConvert.DeserializeObject <AlprResult>(responseString); return(result); } }
public void Debug(string template, params object[] values) { if (_inner.IsEnabled(LogEventLevel.Debug)) { _inner.Debug(template, values); } }
public void SerilogAsync() { for (int i = 0; i < _iterations; i++) { var str = i.ToString(); _serilogAsyncLogger.Debug($"This is a message with two params! {i}, {str}"); } }
private static async Task StartEventStoreConnection(string[] args) { _log.Debug("Building event store connection"); _eventStoreConnection = BuildEventStoreConnection(args); _log.Information("Starting event store connection"); await _eventStoreConnection.ConnectAsync(); _log.Information("Event store connection started"); }
private async Task EventAppeared(EventStoreCatchUpSubscription subscription, ResolvedEvent resolvedEvent) { if (resolvedEvent.Event.EventType.StartsWith("$")) { return; } var @event = resolvedEvent.Deserialize(); log.Debug($"Projecting event: {@event.GetType().Name}"); await Task.WhenAll(projections.Select(projection => projection.Project(@event))); }
public async Task <CommandResponse> Execute(Message message) { if (message is null) { throw new ArgumentNullException(nameof(message)); } _logger.Debug("- Ping -"); var response = new CommandResponse(CommandStatus.Success, "Pong !"); await message.Channel.ReplyToAsync(message, response).ConfigureAwait(false); return(response); }
private bool TableHasContent(string tableName) { var commandText = "SELECT CASE WHEN EXISTS" + $"(SELECT TOP 1 * FROM {tableName})" + "THEN 1 ELSE 0 END"; logger.Debug(commandText); var command = dataHelper.CreateCommand(commandText); return((int)command.ExecuteScalar() == 1); }
public IActionResult Authentication([FromBody] LoginInfo loginInfo) { try { TokenInfo tokenInfo = new TokenInfo(); var apiUserInfo = this.apikeyValidService.Validate(loginInfo.APIKey); logger.Debug("apiUserInfo : {apiUserInfo}", JsonConvert.SerializeObject(apiUserInfo)); if (apiUserInfo == null) { return(NotFound("유효한 apiKey가 아닙니다.")); } var user = this.loginService.Login(loginInfo.Id, loginInfo.Password); logger.Debug("user : {@user}", JsonConvert.SerializeObject(user)); if (user == null) { return(NotFound("아이디 또는 패스워드가 올바르지 않습니다.")); } tokenInfo = this.tokenService.GetToken(user, apiUserInfo); if (tokenInfo == null) { return(NotFound("토큰 발급에 실패했습니다.")); } return(Ok(tokenInfo)); } catch (Exception ex) { logger.Error(ex, "인증에 실패했습니다."); return(NotFound("인증에 실패했습니다.")); } }
public override async Task <CommandResponse> Execute(Message message) { if (message is null) { throw new ArgumentNullException(nameof(message)); } try { if (_dumpDataService.Status == Enums.DumpDataStatus.Ready) { _logger.Debug(message.Content); var parameters = message.Content.Split(" ").Skip(1).ToList(); if (!parameters.Any()) { parameters.Add("The Free Nations Region"); } string regionName = Helpers.ToID(string.Join(" ", parameters)); var request = new Request($"region={regionName}&q=name+numnations+founded+foundedtime+tags+delegate+census+power;mode=score;scale=65", ResponseFormat.Xml); _dispatcher.Dispatch(request, 0); await request.WaitForResponseAsync(_token).ConfigureAwait(false); await ProcessResultAsync(request, regionName).ConfigureAwait(false); CommandResponse commandResponse = _responseBuilder.Build(); await message.Channel.ReplyToAsync(message, commandResponse).ConfigureAwait(false); return(commandResponse); } else if (_dumpDataService.Status == Enums.DumpDataStatus.Updating) { return(await FailCommandAsync(message, "Dump Information is currently updating. Please try again later. Avg. ETA: ~15 s", Discord.Color.Gold, "Dump Data updating").ConfigureAwait(false)); } else { return(await FailCommandAsync(message, $"Dump Data Service is in Status ({_dumpDataService.Status}) from which it can not recover on its own. Please contact the bot administrator.").ConfigureAwait(false)); } } catch (TaskCanceledException e) { _logger.Error(e.ToString()); return(await FailCommandAsync(message, "Request/Command has been canceled. Sorry :(").ConfigureAwait(false)); } catch (HttpRequestFailedException e) { _logger.Error(e.ToString()); return(await FailCommandAsync(message, e.Message).ConfigureAwait(false)); } catch (Exception e) { _logger.Error(e.ToString()); return(await FailCommandAsync(message, "An unexpected error occured. Please contact the bot administrator.").ConfigureAwait(false)); } }
protected TaskManager(string name) { // Serilog Configuration Log = Processor.Log.CreateLog(name); Log.Debug("Created new log: " + name); blKeepRunning = true; ewh = new AutoResetEvent(false); // Start new read thread cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; t = Task.Factory.StartNew(() => Process(), ct); }
private void ConfigureSerilog() { var logConfig = new LoggerConfiguration() .ReadFrom .Configuration(Configuration); var esLogConfig = new ElasticSearchLogConfigurator(Configuration); esLogConfig.Configure(logConfig); Log.Logger = logConfig.CreateLogger(); StartupLogger = Log.Logger; StartupLogger.Debug("Completed logging configuration..."); }
public void Fact3() { DummySink sink = new DummySink(); LoggerSourceContextLevelOverrides switches = new LoggerSourceContextLevelOverrides(LogEventLevel.Warning, KeyValuePair.Create("A", LogEventLevel.Debug), KeyValuePair.Create("2", LogEventLevel.Debug), KeyValuePair.Create("3", LogEventLevel.Debug), KeyValuePair.Create("4", LogEventLevel.Debug), KeyValuePair.Create("5", LogEventLevel.Debug), KeyValuePair.Create("6", LogEventLevel.Debug), KeyValuePair.Create("7", LogEventLevel.Debug), KeyValuePair.Create("8", LogEventLevel.Debug), KeyValuePair.Create("9", LogEventLevel.Debug), KeyValuePair.Create("10", LogEventLevel.Debug) ); Logger logger = new LoggerConfiguration() .Filter().MinimumLevel() .WriteTo.Logger(c => c .Filter().Overrides(switches) .WriteTo.Sink(sink)) .CreateLogger(); Logger defaultLogger = new LoggerConfiguration() .Filter().MinimumLevel() .WriteTo.Logger(c => c .Filter().Overrides(switches) .WriteTo.Sink(sink)) .CreateLogger(); Serilog.ILogger abLogger = logger.ForContext(Constants.SourceContextPropertyName, "A.B"); Serilog.ILogger bLogger = logger.ForContext(Constants.SourceContextPropertyName, "B"); for (int i = 0; i < 100_000; i++) { bLogger.Information("b"); } Assert.Empty(sink.Events); sink.Events.Clear(); for (int i = 0; i < 100_000; i++) { abLogger.Debug("ab"); } Assert.Equal(100000, sink.Events.Count); sink.Events.Clear(); }
/// <summary> /// Constructor. /// </summary> /// <param name="configuration"></param> /// <param name="env"></param> public Startup(IConfiguration configuration, IWebHostEnvironment env) { _configuration = configuration; _logger = new LoggerConfiguration() .ReadFrom.Configuration(_configuration) .Enrich.WithProperty("Version", ReflectionUtils.GetAssemblyVersion <Startup>()) .CreateLogger(); _applicationName = _configuration.GetValue <string>(ApplicationNameKey) ?? throw new ArgumentNullException(ApplicationNameKey); _logger.Information("Starting {ApplicationName} {ApplicationVersion}", _applicationName, ReflectionUtils.GetAssemblyVersion <Program>()); if (env.IsDevelopment()) { _logger.Debug(_configuration.Dump()); } }
public async Task OpenMarket() { _logger.Debug("[ENTER] [OpenMarket]"); await _marketStateLock.WaitAsync(); try { if (MarketState != MarketState.Open) { _logger.Debug("[DGB] [OpenMarket]: Opening MarketState."); _timer = new Timer(UpdateStockPrices, null, _updateInterval, _updateInterval); MarketState = MarketState.Open; await BroadcastMarketStateChange(MarketState.Open); } else { _logger.Debug("[DGB] [OpenMarket]: MarketState already open."); } } finally { _marketStateLock.Release(); } }
public async Task <CommandResponse> Execute(Message message) { if (message is null) { throw new ArgumentNullException(nameof(message)); } try { _logger.Debug(message.Content); var parameters = message.Content.Split(" ").Skip(1); if (parameters.Any()) { string nationName = Helpers.ToID(string.Join(" ", parameters)); var request = new Request($"nation={nationName}&q=flag+wa+gavote+scvote+fullname+freedom+demonym2plural+category+population+region+founded+foundedtime+influence+lastactivity+census;mode=score;scale=0+1+2+65+66+80", ResponseFormat.Xml); _dispatcher.Dispatch(request, 0); await request.WaitForResponseAsync(token).ConfigureAwait(false); await ProcessResultAsync(request, nationName).ConfigureAwait(false); CommandResponse commandResponse = _responseBuilder.Build(); await message.Channel.ReplyToAsync(message, commandResponse).ConfigureAwait(false); return(commandResponse); } else { return(await FailCommandAsync(message, "No parameter passed.").ConfigureAwait(false)); } } catch (TaskCanceledException e) { _logger.Error(e.ToString()); return(await FailCommandAsync(message, "Request/Command has been canceled. Sorry :(").ConfigureAwait(false)); } catch (HttpRequestFailedException e) { _logger.Error(e.ToString()); return(await FailCommandAsync(message, e.Message).ConfigureAwait(false)); } catch (Exception e) { _logger.Error(e.ToString()); return(await FailCommandAsync(message, "An unexpected error occured. Please contact the bot administrator.").ConfigureAwait(false)); } }