diff --git a/src/Stratis.Bitcoin.Features.BlockStore/AddressIndexing/AddressIndexRepository.cs b/src/Stratis.Bitcoin.Features.BlockStore/AddressIndexing/AddressIndexRepository.cs index 5c4fa765fb..763dc58d9f 100644 --- a/src/Stratis.Bitcoin.Features.BlockStore/AddressIndexing/AddressIndexRepository.cs +++ b/src/Stratis.Bitcoin.Features.BlockStore/AddressIndexing/AddressIndexRepository.cs @@ -32,7 +32,7 @@ public AddressIndexerData GetOrCreateAddress(string address) { if (!this.TryGetValue(address, out AddressIndexerData data)) { - this.logger.Debug("Not found in cache."); + this.logger.LogDebug("Not found in cache."); data = this.addressIndexerDataCollection.FindById(address) ?? new AddressIndexerData() { Address = address, BalanceChanges = new List() }; } @@ -82,7 +82,7 @@ public void SaveAllItems() { CacheItem[] dirtyItems = this.Keys.Where(x => x.Dirty).ToArray(); - this.logger.Debug("Saving {0} dirty items.", dirtyItems.Length); + this.logger.LogDebug("Saving {0} dirty items.", dirtyItems.Length); List toUpsert = dirtyItems.Select(x => x.Value).ToList(); @@ -91,7 +91,7 @@ public void SaveAllItems() foreach (CacheItem dirtyItem in dirtyItems) dirtyItem.Dirty = false; - this.logger.Debug("Saved dirty items."); + this.logger.LogDebug("Saved dirty items."); } } } diff --git a/src/Stratis.Bitcoin.Features.BlockStore/AddressIndexing/AddressIndexer.cs b/src/Stratis.Bitcoin.Features.BlockStore/AddressIndexing/AddressIndexer.cs index 970f24be31..7c335a68bf 100644 --- a/src/Stratis.Bitcoin.Features.BlockStore/AddressIndexing/AddressIndexer.cs +++ b/src/Stratis.Bitcoin.Features.BlockStore/AddressIndexing/AddressIndexer.cs @@ -183,7 +183,7 @@ public void Initialize() // The transaction index is needed in the event of a reorg. if (!this.storeSettings.AddressIndex) { - this.logger.Trace("(-)[DISABLED]"); + this.logger.LogTrace("(-)[DISABLED]"); return; } @@ -194,7 +194,7 @@ public void Initialize() this.addressIndexRepository = new AddressIndexRepository(this.db); - this.logger.Debug("Address indexing is enabled."); + this.logger.LogDebug("Address indexing is enabled."); this.tipDataStore = this.db.GetCollection(DbTipDataKey); @@ -202,7 +202,7 @@ public void Initialize() { AddressIndexerTipData tipData = this.tipDataStore.FindAll().FirstOrDefault(); - this.logger.Debug("Tip data: '{0}'.", tipData == null ? "null" : tipData.ToString()); + this.logger.LogDebug("Tip data: '{0}'.", tipData == null ? "null" : tipData.ToString()); this.IndexerTip = tipData == null ? this.chainIndexer.Genesis : this.consensusManager.Tip.FindAncestorOrSelf(new uint256(tipData.TipHashBytes)); @@ -222,7 +222,7 @@ public void Initialize() this.RewindAndSave(this.IndexerTip); - this.logger.Debug("Indexer initialized at '{0}'.", this.IndexerTip); + this.logger.LogDebug("Indexer initialized at '{0}'.", this.IndexerTip); this.indexingTask = Task.Run(async () => await this.IndexAddressesContinuouslyAsync().ConfigureAwait(false)); @@ -239,18 +239,18 @@ private async Task IndexAddressesContinuouslyAsync() { if (this.dateTimeProvider.GetUtcNow() - this.lastFlushTime > this.flushChangesInterval) { - this.logger.Debug("Flushing changes."); + this.logger.LogDebug("Flushing changes."); this.SaveAll(); this.lastFlushTime = this.dateTimeProvider.GetUtcNow(); - this.logger.Debug("Flush completed."); + this.logger.LogDebug("Flush completed."); } if (this.cancellation.IsCancellationRequested) { - this.logger.Debug("Cancelled loop."); + this.logger.LogDebug("Cancelled loop."); break; } @@ -258,7 +258,7 @@ private async Task IndexAddressesContinuouslyAsync() if (nextHeader == null) { - this.logger.Debug("Next header wasn't found. Waiting."); + this.logger.LogDebug("Next header wasn't found. Waiting."); try { @@ -275,7 +275,7 @@ private async Task IndexAddressesContinuouslyAsync() { ChainedHeader lastCommonHeader = nextHeader.FindFork(this.IndexerTip); - this.logger.Debug("Reorganization detected. Rewinding till '{0}'.", lastCommonHeader); + this.logger.LogDebug("Reorganization detected. Rewinding till '{0}'.", lastCommonHeader); this.RewindAndSave(lastCommonHeader); @@ -294,7 +294,7 @@ private async Task IndexAddressesContinuouslyAsync() if (blockToProcess == null) { - this.logger.Debug("Next block wasn't found. Waiting."); + this.logger.LogDebug("Next block wasn't found. Waiting."); try { @@ -322,7 +322,7 @@ private async Task IndexAddressesContinuouslyAsync() if (!success) { - this.logger.Debug("Failed to process next block. Waiting."); + this.logger.LogDebug("Failed to process next block. Waiting."); try { @@ -357,7 +357,7 @@ private void RewindAndSave(ChainedHeader rewindToHeader) indexData.BalanceChanges.RemoveAll(x => x.BalanceChangedHeight > rewindToHeader.Height); } - this.logger.Debug("Rewinding changes for {0} addresses.", affectedAddresses.Count); + this.logger.LogDebug("Rewinding changes for {0} addresses.", affectedAddresses.Count); // Rewind all the way back to the fork point. this.outpointsRepository.RewindDataAboveHeight(rewindToHeader.Height); @@ -370,14 +370,14 @@ private void RewindAndSave(ChainedHeader rewindToHeader) private void SaveAll() { - this.logger.Debug("Saving address indexer."); + this.logger.LogDebug("Saving address indexer."); lock (this.lockObject) { - this.logger.Debug("Saving addr indexer repo."); + this.logger.LogDebug("Saving addr indexer repo."); this.addressIndexRepository.SaveAllItems(); - this.logger.Debug("Saving outpoints repo."); + this.logger.LogDebug("Saving outpoints repo."); this.outpointsRepository.SaveAllItems(); AddressIndexerTipData tipData = this.tipDataStore.FindAll().FirstOrDefault(); @@ -388,13 +388,13 @@ private void SaveAll() tipData.Height = this.IndexerTip.Height; tipData.TipHashBytes = this.IndexerTip.HashBlock.ToBytes(); - this.logger.Debug("Saving tip data."); + this.logger.LogDebug("Saving tip data."); this.tipDataStore.Upsert(tipData); this.lastSavedHeight = this.IndexerTip.Height; } - this.logger.Debug("Address indexer saved."); + this.logger.LogDebug("Address indexer saved."); } private void AddInlineStats(StringBuilder benchLog) @@ -411,7 +411,7 @@ private void AddInlineStats(StringBuilder benchLog) /// true if block was sucessfully processed. private bool ProcessBlock(Block block, ChainedHeader header) { - this.logger.Trace("Processing block " + header.ToString()); + this.logger.LogTrace("Processing block " + header.ToString()); lock (this.lockObject) { @@ -460,8 +460,8 @@ private bool ProcessBlock(Block block, ChainedHeader header) if (!this.outpointsRepository.TryGetOutPointData(consumedOutput, out OutPointData consumedOutputData)) { - this.logger.Error("Missing outpoint data for {0}.", consumedOutput); - this.logger.Trace("(-)[MISSING_OUTPOINTS_DATA]"); + this.logger.LogError("Missing outpoint data for {0}.", consumedOutput); + this.logger.LogTrace("(-)[MISSING_OUTPOINTS_DATA]"); throw new Exception($"Missing outpoint data for {consumedOutput}"); } @@ -523,7 +523,7 @@ private bool ProcessBlock(Block block, ChainedHeader header) this.outpointsRepository.RemoveOutPointData(consumedOutPoint); } - this.logger.Trace("Block processed."); + this.logger.LogTrace("Block processed."); return true; } @@ -554,7 +554,7 @@ private void ProcessBalanceChangeLocked(int height, string address, Money amount { this.addressIndexRepository.AddOrUpdate(indexData.Address, indexData, indexData.BalanceChanges.Count + 1); - this.logger.Trace("(-)[TOO_FEW_CHANGE_RECORDS]"); + this.logger.LogTrace("(-)[TOO_FEW_CHANGE_RECORDS]"); return; } @@ -574,14 +574,14 @@ private void ProcessBalanceChangeLocked(int height, string address, Money amount if ((change.BalanceChangedHeight) < heightThreshold && i < CompactionAmount) { - this.logger.Debug("Balance change: {0} was selected for compaction. Compacted balance now: {1}.", change, compacted[0].Satoshi); + this.logger.LogDebug("Balance change: {0} was selected for compaction. Compacted balance now: {1}.", change, compacted[0].Satoshi); if (change.Deposited) compacted[0].Satoshi += change.Satoshi; else compacted[0].Satoshi -= change.Satoshi; - this.logger.Debug("New compacted balance: {0}.", compacted[0].Satoshi); + this.logger.LogDebug("New compacted balance: {0}.", compacted[0].Satoshi); } else compacted.Add(change); @@ -620,7 +620,7 @@ public AddressBalancesResult GetAddressBalances(string[] addresses, int minConfi long balance = indexData.BalanceChanges.Where(x => x.BalanceChangedHeight <= maxAllowedHeight).CalculateBalance(); - this.logger.Debug("Address: {0}, balance: {1}.", address, balance); + this.logger.LogDebug("Address: {0}, balance: {1}.", address, balance); result.Balances.Add(new AddressBalanceResult(address, new Money(balance))); } @@ -735,13 +735,13 @@ public LastBalanceDecreaseTransactionModel GetLastBalanceDecreaseTransaction(str { if (this.addressIndexRepository == null) { - this.logger.Trace("(-)[NOT_INITIALIZED]"); + this.logger.LogTrace("(-)[NOT_INITIALIZED]"); return (false, "Address indexer is not initialized."); } if (!this.IsSynced()) { - this.logger.Trace("(-)[NOT_SYNCED]"); + this.logger.LogTrace("(-)[NOT_SYNCED]"); return (false, "Address indexer is not synced."); } @@ -751,7 +751,7 @@ public LastBalanceDecreaseTransactionModel GetLastBalanceDecreaseTransaction(str /// public void Dispose() { - this.logger.Debug("Disposing."); + this.logger.LogDebug("Disposing."); this.cancellation.Cancel(); @@ -759,7 +759,7 @@ public void Dispose() this.db?.Dispose(); - this.logger.Debug("Disposed."); + this.logger.LogDebug("Disposed."); } } } diff --git a/src/Stratis.Bitcoin.Features.BlockStore/AddressIndexing/AddressIndexerOutpointsRepository.cs b/src/Stratis.Bitcoin.Features.BlockStore/AddressIndexing/AddressIndexerOutpointsRepository.cs index 0501074bc5..852f486aed 100644 --- a/src/Stratis.Bitcoin.Features.BlockStore/AddressIndexing/AddressIndexerOutpointsRepository.cs +++ b/src/Stratis.Bitcoin.Features.BlockStore/AddressIndexing/AddressIndexerOutpointsRepository.cs @@ -74,7 +74,7 @@ public bool TryGetOutPointData(OutPoint outPoint, out OutPointData outPointData) { if (this.TryGetValue(outPoint.ToString(), out outPointData)) { - this.logger.Trace("(-)[FOUND_IN_CACHE]:true"); + this.logger.LogTrace("(-)[FOUND_IN_CACHE]:true"); return true; } @@ -84,7 +84,7 @@ public bool TryGetOutPointData(OutPoint outPoint, out OutPointData outPointData) if (outPointData != null) { this.AddOutPointData(outPointData); - this.logger.Trace("(-)[FOUND_IN_DATABASE]:true"); + this.logger.LogTrace("(-)[FOUND_IN_DATABASE]:true"); return true; } @@ -93,7 +93,7 @@ public bool TryGetOutPointData(OutPoint outPoint, out OutPointData outPointData) public void SaveAllItems() { - this.logger.Debug("Saving all items."); + this.logger.LogDebug("Saving all items."); lock (this.LockObject) { CacheItem[] dirtyItems = this.Keys.Where(x => x.Dirty).ToArray(); @@ -102,7 +102,7 @@ public void SaveAllItems() foreach (CacheItem dirtyItem in dirtyItems) dirtyItem.Dirty = false; - this.logger.Debug("{0} items saved.", dirtyItems.Length); + this.logger.LogDebug("{0} items saved.", dirtyItems.Length); } } @@ -123,9 +123,9 @@ public void PurgeOldRewindData(int height) { lock (this.LockObject) { - this.logger.Info("AddressIndexer: started purging rewind data items."); + this.logger.LogInformation("AddressIndexer: started purging rewind data items."); int purgedCount = this.addressIndexerRewindData.Delete(x => x.BlockHeight < height); - this.logger.Info("AddressIndexer: Purged {0} rewind data items.", purgedCount); + this.logger.LogInformation("AddressIndexer: Purged {0} rewind data items.", purgedCount); } } @@ -137,7 +137,7 @@ public void RewindDataAboveHeight(int height) { IEnumerable toRestore = this.addressIndexerRewindData.Find(x => x.BlockHeight > height); - this.logger.Debug("Restoring data for {0} blocks.", toRestore.Count()); + this.logger.LogDebug("Restoring data for {0} blocks.", toRestore.Count()); foreach (AddressIndexerRewindData rewindData in toRestore) { diff --git a/src/Stratis.Bitcoin.Features.BlockStore/Repositories/LevelDbBlockRepository.cs b/src/Stratis.Bitcoin.Features.BlockStore/Repositories/LevelDbBlockRepository.cs index b02a9a7657..52dc357c29 100644 --- a/src/Stratis.Bitcoin.Features.BlockStore/Repositories/LevelDbBlockRepository.cs +++ b/src/Stratis.Bitcoin.Features.BlockStore/Repositories/LevelDbBlockRepository.cs @@ -86,7 +86,7 @@ public Transaction GetTransactionById(uint256 trxid) if (!this.TxIndex) { - this.logger.Trace("(-)[TX_INDEXING_DISABLED]:null"); + this.logger.LogTrace("(-)[TX_INDEXING_DISABLED]:null"); return default(Transaction); } @@ -102,7 +102,7 @@ public Transaction GetTransactionById(uint256 trxid) if (transactionRow == null) { - this.logger.Trace("(-)[NO_BLOCK]:null"); + this.logger.LogTrace("(-)[NO_BLOCK]:null"); return null; } @@ -123,7 +123,7 @@ public Transaction GetTransactionById(uint256 trxid) { if (!this.TxIndex) { - this.logger.Trace("(-)[TX_INDEXING_DISABLED]:null"); + this.logger.LogTrace("(-)[TX_INDEXING_DISABLED]:null"); return null; } @@ -139,7 +139,7 @@ public Transaction GetTransactionById(uint256 trxid) if (alreadyFetched) { - this.logger.Debug("Duplicated transaction encountered. Tx id: '{0}'.", trxids[i]); + this.logger.LogDebug("Duplicated transaction encountered. Tx id: '{0}'.", trxids[i]); txes[i] = txes.First(x => x.GetHash() == trxids[i]); continue; @@ -154,7 +154,7 @@ public Transaction GetTransactionById(uint256 trxid) byte[] transactionRow = this.leveldb.Get(BlockRepositoryConstants.TransactionTableName, trxids[i].ToBytes()); if (transactionRow == null) { - this.logger.Trace("(-)[NO_TX_ROW]:null"); + this.logger.LogTrace("(-)[NO_TX_ROW]:null"); return null; } @@ -162,7 +162,7 @@ public Transaction GetTransactionById(uint256 trxid) if (blockRow != null) { - this.logger.Trace("(-)[NO_BLOCK]:null"); + this.logger.LogTrace("(-)[NO_BLOCK]:null"); return null; } @@ -183,7 +183,7 @@ public uint256 GetBlockIdByTransactionId(uint256 trxid) if (!this.TxIndex) { - this.logger.Trace("(-)[NO_TXINDEX]:null"); + this.logger.LogTrace("(-)[NO_TXINDEX]:null"); return default(uint256); } @@ -299,7 +299,7 @@ public void ReIndex() warningMessage.AppendLine("".PadRight(133, '=')); warningMessage.AppendLine(); - this.logger.Info(warningMessage.ToString()); + this.logger.LogInformation(warningMessage.ToString()); using (var batch = new WriteBatch()) { var enumerator = this.leveldb.GetEnumerator(); @@ -316,7 +316,7 @@ public void ReIndex() // inform the user about the ongoing operation if (++rowCount % 1000 == 0) { - this.logger.Info("Reindex in process... {0}/{1} blocks processed.", rowCount, totalBlocksCount); + this.logger.LogInformation("Reindex in process... {0}/{1} blocks processed.", rowCount, totalBlocksCount); } } } @@ -324,7 +324,7 @@ public void ReIndex() this.leveldb.Write(batch, new WriteOptions() { Sync = true }); } - this.logger.Info("Reindex completed successfully."); + this.logger.LogInformation("Reindex completed successfully."); } else { @@ -499,13 +499,13 @@ public List GetBlocksFromHashes(List hashes) { results[key.Item1] = this.dBreezeSerializer.Deserialize(blockRow); - this.logger.Debug("Block hash '{0}' loaded from the store.", key.Item1); + this.logger.LogDebug("Block hash '{0}' loaded from the store.", key.Item1); } else { results[key.Item1] = null; - this.logger.Debug("Block hash '{0}' not found in the store.", key.Item1); + this.logger.LogDebug("Block hash '{0}' not found in the store.", key.Item1); } } diff --git a/src/Stratis.Bitcoin.Features.BlockStore/Repositories/RocksDbBlockRepository.cs b/src/Stratis.Bitcoin.Features.BlockStore/Repositories/RocksDbBlockRepository.cs index 510e480f31..4b9fc03490 100644 --- a/src/Stratis.Bitcoin.Features.BlockStore/Repositories/RocksDbBlockRepository.cs +++ b/src/Stratis.Bitcoin.Features.BlockStore/Repositories/RocksDbBlockRepository.cs @@ -83,7 +83,7 @@ public Transaction GetTransactionById(uint256 trxid) if (!this.TxIndex) { - this.logger.Trace("(-)[TX_INDEXING_DISABLED]:null"); + this.logger.LogTrace("(-)[TX_INDEXING_DISABLED]:null"); return default; } @@ -99,7 +99,7 @@ public Transaction GetTransactionById(uint256 trxid) if (transactionRow == null) { - this.logger.Trace("(-)[NO_BLOCK]:null"); + this.logger.LogTrace("(-)[NO_BLOCK]:null"); return null; } @@ -120,7 +120,7 @@ public Transaction GetTransactionById(uint256 trxid) { if (!this.TxIndex) { - this.logger.Trace("(-)[TX_INDEXING_DISABLED]:null"); + this.logger.LogTrace("(-)[TX_INDEXING_DISABLED]:null"); return null; } @@ -136,7 +136,7 @@ public Transaction GetTransactionById(uint256 trxid) if (alreadyFetched) { - this.logger.Debug("Duplicated transaction encountered. Tx id: '{0}'.", trxids[i]); + this.logger.LogDebug("Duplicated transaction encountered. Tx id: '{0}'.", trxids[i]); txes[i] = txes.First(x => x.GetHash() == trxids[i]); continue; @@ -151,7 +151,7 @@ public Transaction GetTransactionById(uint256 trxid) byte[] transactionRow = this.rocksDb.Get(BlockRepositoryConstants.TransactionTableName, trxids[i].ToBytes()); if (transactionRow == null) { - this.logger.Trace("(-)[NO_TX_ROW]:null"); + this.logger.LogTrace("(-)[NO_TX_ROW]:null"); return null; } @@ -159,7 +159,7 @@ public Transaction GetTransactionById(uint256 trxid) if (blockRow != null) { - this.logger.Trace("(-)[NO_BLOCK]:null"); + this.logger.LogTrace("(-)[NO_BLOCK]:null"); return null; } @@ -180,7 +180,7 @@ public uint256 GetBlockIdByTransactionId(uint256 trxid) if (!this.TxIndex) { - this.logger.Trace("(-)[NO_TXINDEX]:null"); + this.logger.LogTrace("(-)[NO_TXINDEX]:null"); return default; } @@ -295,7 +295,7 @@ public void ReIndex() warningMessage.AppendLine("".PadRight(133, '=')); warningMessage.AppendLine(); - this.logger.Info(warningMessage.ToString()); + this.logger.LogInformation(warningMessage.ToString()); using (var batch = new WriteBatch()) { var enumerator = this.rocksDb.NewIterator(); @@ -312,7 +312,7 @@ public void ReIndex() // inform the user about the ongoing operation if (++rowCount % 1000 == 0) { - this.logger.Info("Reindex in process... {0}/{1} blocks processed.", rowCount, totalBlocksCount); + this.logger.LogInformation("Reindex in process... {0}/{1} blocks processed.", rowCount, totalBlocksCount); } } } @@ -320,7 +320,7 @@ public void ReIndex() this.rocksDb.Write(batch); } - this.logger.Info("Reindex completed successfully."); + this.logger.LogInformation("Reindex completed successfully."); } else { @@ -495,13 +495,13 @@ public List GetBlocksFromHashes(List hashes) { results[key.Item1] = this.dBreezeSerializer.Deserialize(blockRow); - this.logger.Debug("Block hash '{0}' loaded from the store.", key.Item1); + this.logger.LogDebug("Block hash '{0}' loaded from the store.", key.Item1); } else { results[key.Item1] = null; - this.logger.Debug("Block hash '{0}' not found in the store.", key.Item1); + this.logger.LogDebug("Block hash '{0}' not found in the store.", key.Item1); } } diff --git a/src/Stratis.Bitcoin.Features.Consensus/CoinViews/Coindb/LeveldbCoindb.cs b/src/Stratis.Bitcoin.Features.Consensus/CoinViews/Coindb/LeveldbCoindb.cs index c842640504..0011906fe8 100644 --- a/src/Stratis.Bitcoin.Features.Consensus/CoinViews/Coindb/LeveldbCoindb.cs +++ b/src/Stratis.Bitcoin.Features.Consensus/CoinViews/Coindb/LeveldbCoindb.cs @@ -86,7 +86,7 @@ public void Initialize(ChainedHeader chainTip) byte[] row2 = (current.Height > 1) ? this.leveldb.Get(new byte[] { rewindTable }.Concat(BitConverter.GetBytes(current.Height - 1)).ToArray()) : new byte[] { }; if (row2 != null) { - this.logger.Info("Fixing the coin db."); + this.logger.LogInformation("Fixing the coin db."); var rows = new Dictionary(); @@ -134,12 +134,12 @@ public void Initialize(ChainedHeader chainTip) if (this.GetTipHash() == null) this.SetBlockHash(new HashHeightPair(genesis.GetHash(), 0)); - this.logger.Info("Coinview initialized with tip '{0}'.", this.persistedCoinviewTip); + this.logger.LogInformation("Coinview initialized with tip '{0}'.", this.persistedCoinviewTip); } private void EnsureCoinDatabaseIntegrity(ChainedHeader chainTip) { - this.logger.Info("Checking coin database integrity..."); + this.logger.LogInformation("Checking coin database integrity..."); var heightToCheck = chainTip.Height; @@ -158,13 +158,13 @@ private void EnsureCoinDatabaseIntegrity(ChainedHeader chainTip) { for (int height = heightToCheck - 1; height > chainTip.Height; height--) { - this.logger.Info($"Fixing coin database, deleting rewind data at height {height} above tip '{chainTip}'."); + this.logger.LogInformation($"Fixing coin database, deleting rewind data at height {height} above tip '{chainTip}'."); RewindInternal(batch, height); } } - this.logger.Info("Coin database integrity good."); + this.logger.LogInformation("Coin database integrity good."); } private void SetBlockHash(HashHeightPair nextBlockHash) @@ -201,7 +201,7 @@ public FetchCoinsResponse FetchCoins(OutPoint[] utxos) byte[] row = this.leveldb.Get(new byte[] { coinsTable }.Concat(outPoint.ToBytes()).ToArray()); Coins outputs = row != null ? this.dBreezeSerializer.Deserialize(row) : null; - this.logger.Debug("Outputs for '{0}' were {1}.", outPoint, outputs == null ? "NOT loaded" : "loaded"); + this.logger.LogDebug("Outputs for '{0}' were {1}.", outPoint, outputs == null ? "NOT loaded" : "loaded"); res.UnspentOutputs.Add(outPoint, new UnspentOutput(outPoint, outputs)); } @@ -221,7 +221,7 @@ public void SaveChanges(IList unspentOutputs, HashHeightPair oldB HashHeightPair current = this.GetTipHash(); if (current != oldBlockHash) { - this.logger.Trace("(-)[BLOCKHASH_MISMATCH]"); + this.logger.LogTrace("(-)[BLOCKHASH_MISMATCH]"); throw new InvalidOperationException("Invalid oldBlockHash"); } @@ -232,7 +232,7 @@ public void SaveChanges(IList unspentOutputs, HashHeightPair oldB { if (coin.Coins == null) { - this.logger.Debug("Outputs of transaction ID '{0}' are prunable and will be removed from the database.", coin.OutPoint); + this.logger.LogDebug("Outputs of transaction ID '{0}' are prunable and will be removed from the database.", coin.OutPoint); batch.Delete(new byte[] { coinsTable }.Concat(coin.OutPoint.ToBytes()).ToArray()); } else @@ -246,7 +246,7 @@ public void SaveChanges(IList unspentOutputs, HashHeightPair oldB for (int i = 0; i < toInsert.Count; i++) { var coin = toInsert[i]; - this.logger.Debug("Outputs of transaction ID '{0}' are NOT PRUNABLE and will be inserted into the database. {1}/{2}.", coin.OutPoint, i, toInsert.Count); + this.logger.LogDebug("Outputs of transaction ID '{0}' are NOT PRUNABLE and will be inserted into the database. {1}/{2}.", coin.OutPoint, i, toInsert.Count); batch.Put(new byte[] { coinsTable }.Concat(coin.OutPoint.ToBytes()).ToArray(), this.dBreezeSerializer.Serialize(coin.Coins)); } @@ -257,7 +257,7 @@ public void SaveChanges(IList unspentOutputs, HashHeightPair oldB { var nextRewindIndex = rewindData.PreviousBlockHash.Height + 1; - this.logger.Debug("Rewind state #{0} created.", nextRewindIndex); + this.logger.LogDebug("Rewind state #{0} created.", nextRewindIndex); batch.Put(new byte[] { rewindTable }.Concat(BitConverter.GetBytes(nextRewindIndex).Reverse()).ToArray(), this.dBreezeSerializer.Serialize(rewindData)); } @@ -315,13 +315,13 @@ private HashHeightPair RewindInternal(WriteBatch batch, int height) foreach (OutPoint outPoint in rewindData.OutputsToRemove) { - this.logger.Debug("Outputs of outpoint '{0}' will be removed.", outPoint); + this.logger.LogDebug("Outputs of outpoint '{0}' will be removed.", outPoint); batch.Delete(new byte[] { coinsTable }.Concat(outPoint.ToBytes()).ToArray()); } foreach (RewindDataOutput rewindDataOutput in rewindData.OutputsToRestore) { - this.logger.Debug("Outputs of outpoint '{0}' will be restored.", rewindDataOutput.OutPoint); + this.logger.LogDebug("Outputs of outpoint '{0}' will be restored.", rewindDataOutput.OutPoint); batch.Put(new byte[] { coinsTable }.Concat(rewindDataOutput.OutPoint.ToBytes()).ToArray(), this.dBreezeSerializer.Serialize(rewindDataOutput.Coins)); } @@ -367,7 +367,7 @@ public void GetStake(IEnumerable blocklist) { foreach (StakeItem blockStake in blocklist) { - this.logger.Trace("Loading POS block hash '{0}' from the database.", blockStake.BlockId); + this.logger.LogTrace("Loading POS block hash '{0}' from the database.", blockStake.BlockId); byte[] stakeRow = this.leveldb.Get(new byte[] { stakeTable }.Concat(blockStake.BlockId.ToBytes(false)).ToArray()); if (stakeRow != null) diff --git a/src/Stratis.Bitcoin.Features.Consensus/CoinViews/Coindb/RocksDbCoindb.cs b/src/Stratis.Bitcoin.Features.Consensus/CoinViews/Coindb/RocksDbCoindb.cs index 6667f0c5fa..4f715b61fb 100644 --- a/src/Stratis.Bitcoin.Features.Consensus/CoinViews/Coindb/RocksDbCoindb.cs +++ b/src/Stratis.Bitcoin.Features.Consensus/CoinViews/Coindb/RocksDbCoindb.cs @@ -71,7 +71,7 @@ public void Initialize(ChainedHeader chainTip) byte[] row2 = (current.Height > 1) ? this.rocksDb.Get(new byte[] { rewindTable }.Concat(BitConverter.GetBytes(current.Height - 1)).ToArray()) : new byte[] { }; if (row2 != null) { - this.logger.Info("Fixing the coin db."); + this.logger.LogInformation("Fixing the coin db."); var rows = new Dictionary(); @@ -119,12 +119,12 @@ public void Initialize(ChainedHeader chainTip) if (this.GetTipHash() == null) this.SetBlockHash(new HashHeightPair(genesis.GetHash(), 0)); - this.logger.Info("Coinview initialized with tip '{0}'.", this.persistedCoinviewTip); + this.logger.LogInformation("Coinview initialized with tip '{0}'.", this.persistedCoinviewTip); } private void EnsureCoinDatabaseIntegrity(ChainedHeader chainTip) { - this.logger.Info("Checking coin database integrity..."); + this.logger.LogInformation("Checking coin database integrity..."); var heightToCheck = chainTip.Height; @@ -143,12 +143,12 @@ private void EnsureCoinDatabaseIntegrity(ChainedHeader chainTip) { for (int height = heightToCheck - 1; height > chainTip.Height; height--) { - this.logger.Info($"Fixing coin database, deleting rewind data at height {height} above tip '{chainTip}'."); + this.logger.LogInformation($"Fixing coin database, deleting rewind data at height {height} above tip '{chainTip}'."); RewindInternal(batch, height); } } - this.logger.Info("Coin database integrity good."); + this.logger.LogInformation("Coin database integrity good."); } private void SetBlockHash(HashHeightPair nextBlockHash) @@ -185,7 +185,7 @@ public FetchCoinsResponse FetchCoins(OutPoint[] utxos) byte[] row = this.rocksDb.Get(new byte[] { coinsTable }.Concat(outPoint.ToBytes()).ToArray()); Coins outputs = row != null ? this.dBreezeSerializer.Deserialize(row) : null; - this.logger.Debug("Outputs for '{0}' were {1}.", outPoint, outputs == null ? "NOT loaded" : "loaded"); + this.logger.LogDebug("Outputs for '{0}' were {1}.", outPoint, outputs == null ? "NOT loaded" : "loaded"); res.UnspentOutputs.Add(outPoint, new UnspentOutput(outPoint, outputs)); } @@ -205,7 +205,7 @@ public void SaveChanges(IList unspentOutputs, HashHeightPair oldB HashHeightPair current = this.GetTipHash(); if (current != oldBlockHash) { - this.logger.Error("(-)[BLOCKHASH_MISMATCH]"); + this.logger.LogError("(-)[BLOCKHASH_MISMATCH]"); throw new InvalidOperationException("Invalid oldBlockHash"); } @@ -216,7 +216,7 @@ public void SaveChanges(IList unspentOutputs, HashHeightPair oldB { if (coin.Coins == null) { - this.logger.Debug("Outputs of transaction ID '{0}' are prunable and will be removed from the database.", coin.OutPoint); + this.logger.LogDebug("Outputs of transaction ID '{0}' are prunable and will be removed from the database.", coin.OutPoint); batch.Delete(new byte[] { coinsTable }.Concat(coin.OutPoint.ToBytes()).ToArray()); } else @@ -230,7 +230,7 @@ public void SaveChanges(IList unspentOutputs, HashHeightPair oldB for (int i = 0; i < toInsert.Count; i++) { var coin = toInsert[i]; - this.logger.Debug("Outputs of transaction ID '{0}' are NOT PRUNABLE and will be inserted into the database. {1}/{2}.", coin.OutPoint, i, toInsert.Count); + this.logger.LogDebug("Outputs of transaction ID '{0}' are NOT PRUNABLE and will be inserted into the database. {1}/{2}.", coin.OutPoint, i, toInsert.Count); batch.Put(new byte[] { coinsTable }.Concat(coin.OutPoint.ToBytes()).ToArray(), this.dBreezeSerializer.Serialize(coin.Coins)); } @@ -241,7 +241,7 @@ public void SaveChanges(IList unspentOutputs, HashHeightPair oldB { var nextRewindIndex = rewindData.PreviousBlockHash.Height + 1; - this.logger.Debug("Rewind state #{0} created.", nextRewindIndex); + this.logger.LogDebug("Rewind state #{0} created.", nextRewindIndex); batch.Put(new byte[] { rewindTable }.Concat(BitConverter.GetBytes(nextRewindIndex).Reverse()).ToArray(), this.dBreezeSerializer.Serialize(rewindData)); } @@ -300,13 +300,13 @@ private HashHeightPair RewindInternal(WriteBatch batch, int height) foreach (OutPoint outPoint in rewindData.OutputsToRemove) { - this.logger.Debug("Outputs of outpoint '{0}' will be removed.", outPoint); + this.logger.LogDebug("Outputs of outpoint '{0}' will be removed.", outPoint); batch.Delete(new byte[] { coinsTable }.Concat(outPoint.ToBytes()).ToArray()); } foreach (RewindDataOutput rewindDataOutput in rewindData.OutputsToRestore) { - this.logger.Debug("Outputs of outpoint '{0}' will be restored.", rewindDataOutput.OutPoint); + this.logger.LogDebug("Outputs of outpoint '{0}' will be restored.", rewindDataOutput.OutPoint); batch.Put(new byte[] { coinsTable }.Concat(rewindDataOutput.OutPoint.ToBytes()).ToArray(), this.dBreezeSerializer.Serialize(rewindDataOutput.Coins)); } @@ -352,7 +352,7 @@ public void GetStake(IEnumerable blocklist) { foreach (StakeItem blockStake in blocklist) { - this.logger.Debug("Loading POS block hash '{0}' from the database.", blockStake.BlockId); + this.logger.LogDebug("Loading POS block hash '{0}' from the database.", blockStake.BlockId); byte[] stakeRow = this.rocksDb.Get(new byte[] { stakeTable }.Concat(blockStake.BlockId.ToBytes(false)).ToArray()); if (stakeRow != null) diff --git a/src/Stratis.Bitcoin.Features.Consensus/ProvenBlockHeaders/RocksDbProvenBlockHeaderRepository.cs b/src/Stratis.Bitcoin.Features.Consensus/ProvenBlockHeaders/RocksDbProvenBlockHeaderRepository.cs index 2e43bdc547..52803ffcc6 100644 --- a/src/Stratis.Bitcoin.Features.Consensus/ProvenBlockHeaders/RocksDbProvenBlockHeaderRepository.cs +++ b/src/Stratis.Bitcoin.Features.Consensus/ProvenBlockHeaders/RocksDbProvenBlockHeaderRepository.cs @@ -117,7 +117,7 @@ public Task PutAsync(SortedDictionary headers, HashHeigh Task task = Task.Run(() => { - this.logger.Debug("({0}.Count():{1})", nameof(headers), headers.Count()); + this.logger.LogDebug("({0}.Count():{1})", nameof(headers), headers.Count()); this.InsertHeaders(headers); diff --git a/src/Stratis.Bitcoin.Features.ExternalAPI/Controllers/ExternalApiController.cs b/src/Stratis.Bitcoin.Features.ExternalAPI/Controllers/ExternalApiController.cs index ece2f5dcc3..8c1d776a9c 100644 --- a/src/Stratis.Bitcoin.Features.ExternalAPI/Controllers/ExternalApiController.cs +++ b/src/Stratis.Bitcoin.Features.ExternalAPI/Controllers/ExternalApiController.cs @@ -71,7 +71,7 @@ public IActionResult EstimateConversionGas() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -93,7 +93,7 @@ public IActionResult EstimateConversionFee() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -115,7 +115,7 @@ public IActionResult GasPrice() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -137,7 +137,7 @@ public IActionResult StratisPrice() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -159,7 +159,7 @@ public IActionResult EthereumPrice() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } diff --git a/src/Stratis.Bitcoin.Features.Interop/Controllers/InteropController.cs b/src/Stratis.Bitcoin.Features.Interop/Controllers/InteropController.cs index ce37273b30..646640311e 100644 --- a/src/Stratis.Bitcoin.Features.Interop/Controllers/InteropController.cs +++ b/src/Stratis.Bitcoin.Features.Interop/Controllers/InteropController.cs @@ -84,7 +84,7 @@ public IActionResult InteropStatusBurnRequests() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -124,7 +124,7 @@ public IActionResult InteropStatusMintRequests() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -160,7 +160,7 @@ public IActionResult InteropStatusVotes() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -188,7 +188,7 @@ public async Task OwnersAsync(DestinationChain destinationChain) } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } @@ -224,7 +224,7 @@ public async Task AddOwnerAsync(DestinationChain destinationChain } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } @@ -260,7 +260,7 @@ public async Task RemoveOwnerAsync(DestinationChain destinationCh } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } @@ -293,7 +293,7 @@ public async Task ConfirmTransactionAsync(DestinationChain destin } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } @@ -331,7 +331,7 @@ public async Task ChangeRequirementAsync(DestinationChain destina } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } @@ -375,7 +375,7 @@ public async Task MultisigTransactionAsync(DestinationChain desti } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } @@ -417,7 +417,7 @@ public async Task MultisigConfirmationsAsync(DestinationChain des } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } @@ -447,7 +447,7 @@ public async Task BalanceAsync(DestinationChain destinationChain, } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } @@ -487,7 +487,7 @@ public IActionResult SetOriginatorForRequest([FromBody] string requestId) } catch (Exception e) { - this.logger.Error("Exception setting conversion request '{0}' to {1} : {2}.", requestId, e.ToString(), ConversionRequestStatus.OriginatorNotSubmitted); + this.logger.LogError("Exception setting conversion request '{0}' to {1} : {2}.", requestId, e.ToString(), ConversionRequestStatus.OriginatorNotSubmitted); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Error", e.Message); } @@ -511,7 +511,7 @@ public IActionResult ResetConversionRequestAsNotOriginator([FromBody] string req } catch (Exception e) { - this.logger.Error("Exception setting conversion request '{0}' to {1} : {2}.", requestId, e.ToString(), ConversionRequestStatus.NotOriginator); + this.logger.LogError("Exception setting conversion request '{0}' to {1} : {2}.", requestId, e.ToString(), ConversionRequestStatus.NotOriginator); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Error", e.Message); } @@ -531,13 +531,13 @@ public IActionResult ReprocessBurnRequest([FromBody] ReprocessBurnRequestModel m try { this.conversionRequestRepository.ReprocessBurnRequest(model.RequestId, model.BlockHeight, ConversionRequestStatus.Unprocessed); - this.logger.Info($"Burn request '{model.RequestId}' will be reprocessed at height {model.BlockHeight}."); + this.logger.LogInformation($"Burn request '{model.RequestId}' will be reprocessed at height {model.BlockHeight}."); return this.Json($"Burn request '{model.RequestId}' will be reprocessed at height {model.BlockHeight}."); } catch (Exception e) { - this.logger.Error("Exception setting burn request '{0}' to be reprocessed : {1}.", model.RequestId, e.ToString()); + this.logger.LogError("Exception setting burn request '{0}' to be reprocessed : {1}.", model.RequestId, e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Error", e.Message); } @@ -562,7 +562,7 @@ public IActionResult PushVoteManually([FromBody] PushManualVoteForRequest model) } catch (Exception e) { - this.logger.Error("Exception manual pushing vote for conversion request '{0}' : {1}.", model.RequestId, e.ToString()); + this.logger.LogError("Exception manual pushing vote for conversion request '{0}' : {1}.", model.RequestId, e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Error", e.Message); } diff --git a/src/Stratis.Bitcoin.Features.Interop/InteropBehavior.cs b/src/Stratis.Bitcoin.Features.Interop/InteropBehavior.cs index b35aec62f9..2e867e9d2f 100644 --- a/src/Stratis.Bitcoin.Features.Interop/InteropBehavior.cs +++ b/src/Stratis.Bitcoin.Features.Interop/InteropBehavior.cs @@ -55,14 +55,14 @@ public override object Clone() /// protected override void AttachCore() { - this.logger.Debug("Attaching behaviour for {0}", this.AttachedPeer.PeerEndPoint.Address); + this.logger.LogDebug("Attaching behaviour for {0}", this.AttachedPeer.PeerEndPoint.Address); this.AttachedPeer.MessageReceived.Register(this.OnMessageReceivedAsync, true); } /// protected override void DetachCore() { - this.logger.Debug("Detaching behaviour for {0}", this.AttachedPeer.PeerEndPoint.Address); + this.logger.LogDebug("Detaching behaviour for {0}", this.AttachedPeer.PeerEndPoint.Address); this.AttachedPeer.MessageReceived.Unregister(this.OnMessageReceivedAsync); } @@ -74,12 +74,12 @@ private async Task OnMessageReceivedAsync(INetworkPeer peer, IncomingMessage mes } catch (OperationCanceledException) { - this.logger.Trace("(-)[CANCELED_EXCEPTION]"); + this.logger.LogTrace("(-)[CANCELED_EXCEPTION]"); return; } catch (Exception ex) { - this.logger.Error("Exception occurred: {0}", ex.ToString()); + this.logger.LogError("Exception occurred: {0}", ex.ToString()); throw; } } @@ -105,7 +105,7 @@ private async Task ProcessMessageAsync(INetworkPeer peer, IncomingMessage messag } catch (OperationCanceledException) { - this.logger.Trace("(-)[CANCELED_EXCEPTION]"); + this.logger.LogTrace("(-)[CANCELED_EXCEPTION]"); } } @@ -114,7 +114,7 @@ private async Task ProcessConversionRequestPayloadAsync(INetworkPeer peer, Conve if (!this.federationManager.IsFederationMember) return; - this.logger.Debug("Conversion request payload request for id '{0}' received from '{1}':'{2}' proposing transaction ID '{4}'.", payload.RequestId, peer.PeerEndPoint.Address, peer.RemoteSocketEndpoint.Address, payload.RequestId, payload.TransactionId); + this.logger.LogDebug("Conversion request payload request for id '{0}' received from '{1}':'{2}' proposing transaction ID '{4}'.", payload.RequestId, peer.PeerEndPoint.Address, peer.RemoteSocketEndpoint.Address, payload.RequestId, payload.TransactionId); if (payload.TransactionId == BigInteger.MinusOne) return; @@ -128,14 +128,14 @@ private async Task ProcessConversionRequestPayloadAsync(INetworkPeer peer, Conve if (!this.federationManager.IsMultisigMember(pubKey)) { - this.logger.Warn("Conversion request payload for '{0}'. Computed pubkey '{1}'.", payload.RequestId, pubKey?.ToHex()); + this.logger.LogWarning("Conversion request payload for '{0}'. Computed pubkey '{1}'.", payload.RequestId, pubKey?.ToHex()); return; } } catch (Exception) { - this.logger.Warn("Received malformed conversion request payload for '{0}'.", payload.RequestId); + this.logger.LogWarning("Received malformed conversion request payload for '{0}'.", payload.RequestId); return; } @@ -154,7 +154,7 @@ private async Task ProcessConversionRequestPayloadAsync(INetworkPeer peer, Conve // We presume that the initial submitter of the transaction must have at least confirmed it. Otherwise just ignore this coordination attempt. if (confirmationCount < 1) { - this.logger.Info("Multisig wallet transaction {0} has no confirmations.", payload.TransactionId); + this.logger.LogInformation("Multisig wallet transaction {0} has no confirmations.", payload.TransactionId); return; } @@ -184,13 +184,13 @@ private async Task ProcessFeeProposalAsync(FeeProposalPayload payload) if (!this.federationManager.IsMultisigMember(pubKey)) { - this.logger.Warn("Received unverified fee proposal payload for '{0}' from pubkey '{1}'.", payload.RequestId, pubKey?.ToHex()); + this.logger.LogWarning("Received unverified fee proposal payload for '{0}' from pubkey '{1}'.", payload.RequestId, pubKey?.ToHex()); return; } } catch (Exception) { - this.logger.Warn("Received malformed fee proposal payload for '{0}'.", payload.RequestId); + this.logger.LogWarning("Received malformed fee proposal payload for '{0}'.", payload.RequestId); return; } @@ -214,13 +214,13 @@ private async Task ProcessFeeAgreeAsync(FeeAgreePayload payload) if (!this.federationManager.IsMultisigMember(pubKey)) { - this.logger.Warn("Received unverified fee vote payload for '{0}' from pubkey '{1}'.", payload.RequestId, pubKey?.ToHex()); + this.logger.LogWarning("Received unverified fee vote payload for '{0}' from pubkey '{1}'.", payload.RequestId, pubKey?.ToHex()); return; } } catch (Exception) { - this.logger.Warn("Received malformed fee vote payload for '{0}'.", payload.RequestId); + this.logger.LogWarning("Received malformed fee vote payload for '{0}'.", payload.RequestId); return; } diff --git a/src/Stratis.Bitcoin.Features.Interop/InteropPoller.cs b/src/Stratis.Bitcoin.Features.Interop/InteropPoller.cs index a6e96dae77..4b69c8b7ef 100644 --- a/src/Stratis.Bitcoin.Features.Interop/InteropPoller.cs +++ b/src/Stratis.Bitcoin.Features.Interop/InteropPoller.cs @@ -127,17 +127,17 @@ public async Task InitializeAsync() if (!this.ethClientProvider.GetAllSupportedChains().Any()) { // There are no chains that are supported and enabled, exit. - this.logger.Debug("Interop disabled."); + this.logger.LogDebug("Interop disabled."); return; } if (!this.federationManager.IsFederationMember) { - this.logger.Debug("Not a federation member."); + this.logger.LogDebug("Not a federation member."); return; } - this.logger.Info($"Interoperability enabled, initializing periodic loop."); + this.logger.LogInformation($"Interoperability enabled, initializing periodic loop."); // Initialize the interop polling loop, to check for interop contract requests. this.interopLoop = this.asyncProvider.CreateAndRunAsyncLoop("PeriodicCheckInterop", async (cancellation) => @@ -145,7 +145,7 @@ public async Task InitializeAsync() if (this.initialBlockDownloadState.IsInitialBlockDownload()) return; - this.logger.Trace("Beginning interop loop."); + this.logger.LogTrace("Beginning interop loop."); try { @@ -153,10 +153,10 @@ public async Task InitializeAsync() } catch (Exception e) { - this.logger.Warn("Exception raised when checking interop requests. {0}", e); + this.logger.LogWarning("Exception raised when checking interop requests. {0}", e); } - this.logger.Trace("Finishing interop loop."); + this.logger.LogTrace("Finishing interop loop."); }, this.nodeLifetime.ApplicationStopping, repeatEvery: TimeSpans.TenSeconds, @@ -168,7 +168,7 @@ public async Task InitializeAsync() if (this.initialBlockDownloadState.IsInitialBlockDownload()) return; - this.logger.Trace("Beginning conversion processing loop."); + this.logger.LogTrace("Beginning conversion processing loop."); try { @@ -176,10 +176,10 @@ public async Task InitializeAsync() } catch (Exception e) { - this.logger.Warn($"Exception raised when checking conversion requests. {e}"); + this.logger.LogWarning($"Exception raised when checking conversion requests. {e}"); } - this.logger.Trace("Finishing conversion processing loop."); + this.logger.LogTrace("Finishing conversion processing loop."); }, this.nodeLifetime.ApplicationStopping, repeatEvery: TimeSpans.TenSeconds, @@ -195,7 +195,7 @@ public async Task InitializeAsync() if (this.initialBlockDownloadState.IsInitialBlockDownload()) return; - this.logger.Debug("Beginning conversion burn transaction polling loop."); + this.logger.LogDebug("Beginning conversion burn transaction polling loop."); try { @@ -209,10 +209,10 @@ public async Task InitializeAsync() } catch (Exception e) { - this.logger.Warn($"Exception raised when polling for conversion burn transactions. {e}"); + this.logger.LogWarning($"Exception raised when polling for conversion burn transactions. {e}"); } - this.logger.Debug("Finishing conversion burn transaction polling loop."); + this.logger.LogDebug("Finishing conversion burn transaction polling loop."); }, this.nodeLifetime.ApplicationStopping, repeatEvery: TimeSpans.TenSeconds, @@ -234,14 +234,14 @@ private async Task LoadLastPolledBlockAsync() else this.lastPolledBlock[supportedChain.Key] = loaded; - this.logger.Info($"Last polled block for {supportedChain.Key} set to {this.lastPolledBlock[supportedChain.Key]}."); + this.logger.LogInformation($"Last polled block for {supportedChain.Key} set to {this.lastPolledBlock[supportedChain.Key]}."); } } private void SaveLastPolledBlock(DestinationChain destinationChain) { this.keyValueRepository.SaveValueJson(string.Format(LastPolledBlockKey, destinationChain), this.lastPolledBlock[destinationChain]); - this.logger.Info($"Last polled block for {destinationChain} saved as {this.lastPolledBlock[destinationChain]}."); + this.logger.LogInformation($"Last polled block for {destinationChain} saved as {this.lastPolledBlock[destinationChain]}."); } /// @@ -264,7 +264,7 @@ private async Task EnsureLastPolledBlockIsSyncedWithChainAsync() private async Task PollBlockForBurnRequestsAsync(KeyValuePair supportedChain, BigInteger blockHeight) { - this.logger.Info("Polling {0} block at height {1} for burn transactions.", supportedChain.Key, blockHeight); + this.logger.LogInformation("Polling {0} block at height {1} for burn transactions.", supportedChain.Key, blockHeight); BlockWithTransactions block = await supportedChain.Value.GetBlockAsync(this.lastPolledBlock[supportedChain.Key]).ConfigureAwait(false); List<(string TransactionHash, BurnFunction Burn)> burns = await supportedChain.Value.GetBurnsFromBlock(block).ConfigureAwait(false); @@ -292,11 +292,11 @@ private async Task CheckInteropNodesAsync() // TODO Add back or refactor so that this is specific per chain (if applicable) // BigInteger balance = await this.ETHClientBase.GetBalanceAsync(this.interopSettings.ETHAccount).ConfigureAwait(false); - this.logger.Info("Current {0} node block height is {1}.", clientForChain.Key, blockHeight); + this.logger.LogInformation("Current {0} node block height is {1}.", clientForChain.Key, blockHeight); } catch (Exception e) { - this.logger.Error("Error checking {0} node status: {1}", clientForChain.Key, e); + this.logger.LogError("Error checking {0} node status: {1}", clientForChain.Key, e); } } } @@ -306,24 +306,24 @@ private async Task CheckInteropNodesAsync() /// private void ProcessBurn(string blockHash, string transactionHash, BurnFunction burn) { - this.logger.Info("Conversion burn transaction '{0}' received from polled block '{1}', sender {2}.", transactionHash, blockHash, burn.FromAddress); + this.logger.LogInformation("Conversion burn transaction '{0}' received from polled block '{1}', sender {2}.", transactionHash, blockHash, burn.FromAddress); lock (this.repositoryLock) { if (this.conversionRequestRepository.Get(transactionHash) != null) { - this.logger.Info("Conversion burn transaction '{0}' already exists, ignoring.", transactionHash); + this.logger.LogInformation("Conversion burn transaction '{0}' already exists, ignoring.", transactionHash); return; } } - this.logger.Info("Conversion burn transaction '{0}' has value {1}.", transactionHash, burn.Amount); + this.logger.LogInformation("Conversion burn transaction '{0}' has value {1}.", transactionHash, burn.Amount); // Get the destination address recorded in the contract call itself. This has the benefit that subsequent burn calls from the same account providing different addresses will not interfere with this call. string destinationAddress = burn.StraxAddress; - this.logger.Info("Conversion burn transaction '{0}' has destination address {1}.", transactionHash, destinationAddress); + this.logger.LogInformation("Conversion burn transaction '{0}' has destination address {1}.", transactionHash, destinationAddress); // Validate that it is a mainchain address here before bothering to add it to the repository. try @@ -332,7 +332,7 @@ private void ProcessBurn(string blockHash, string transactionHash, BurnFunction } catch (Exception) { - this.logger.Warn("Error validating destination address '{0}' for transaction '{1}'.", destinationAddress, transactionHash); + this.logger.LogWarning("Error validating destination address '{0}' for transaction '{1}'.", destinationAddress, transactionHash); return; } @@ -388,18 +388,18 @@ private async Task ProcessConversionRequestsAsync() if (mintRequests == null) { - this.logger.Debug("There are no requests."); + this.logger.LogDebug("There are no requests."); return; } - this.logger.Info("There are {0} unprocessed conversion mint requests.", mintRequests.Count); + this.logger.LogInformation("There are {0} unprocessed conversion mint requests.", mintRequests.Count); foreach (ConversionRequest request in mintRequests) { // Ignore old conversion requests for the time being. if (request.RequestStatus == ConversionRequestStatus.Unprocessed && (this.chainIndexer.Tip.Height - request.BlockHeight) > this.network.Consensus.MaxReorgLength) { - this.logger.Info("Ignoring old conversion mint request '{0}' with status {1} from block height {2}.", request.RequestId, request.RequestStatus, request.BlockHeight); + this.logger.LogInformation("Ignoring old conversion mint request '{0}' with status {1} from block height {2}.", request.RequestId, request.RequestStatus, request.BlockHeight); request.Processed = true; @@ -411,7 +411,7 @@ private async Task ProcessConversionRequestsAsync() continue; } - this.logger.Info("Processing conversion mint request {0} on {1} chain.", request.RequestId, request.DestinationChain); + this.logger.LogInformation("Processing conversion mint request {0} on {1} chain.", request.RequestId, request.DestinationChain); IETHClient clientForDestChain = this.ethClientProvider.GetClientForChain(request.DestinationChain); @@ -440,13 +440,13 @@ private async Task ProcessConversionRequestsAsync() if (originator) { // If this node is the designated transaction originator, it must create and submit the transaction to the multisig. - this.logger.Info("This node selected as originator for transaction '{0}'.", request.RequestId); + this.logger.LogInformation("This node selected as originator for transaction '{0}'.", request.RequestId); request.RequestStatus = ConversionRequestStatus.OriginatorNotSubmitted; } else { - this.logger.Info("This node was not selected as the originator for transaction '{0}'. The originator is: '{1}'.", request.RequestId, designatedMember == null ? "N/A (Overridden)" : designatedMember.PubKey?.ToHex()); + this.logger.LogInformation("This node was not selected as the originator for transaction '{0}'. The originator is: '{1}'.", request.RequestId, designatedMember == null ? "N/A (Overridden)" : designatedMember.PubKey?.ToHex()); request.RequestStatus = ConversionRequestStatus.NotOriginator; } @@ -456,7 +456,7 @@ private async Task ProcessConversionRequestsAsync() case ConversionRequestStatus.OriginatorNotSubmitted: { - this.logger.Info("Conversion not yet submitted, checking which gas price to use."); + this.logger.LogInformation("Conversion not yet submitted, checking which gas price to use."); // First construct the necessary transfer() transaction data, utilising the ABI of the wrapped STRAX ERC20 contract. // When this constructed transaction is actually executed, the transfer's source account will be the account executing the transaction i.e. the multisig contract address. @@ -468,7 +468,7 @@ private async Task ProcessConversionRequestsAsync() if (gasPrice == -1) gasPrice = this.interopSettings.GetSettingsByChain(request.DestinationChain).GasPrice; - this.logger.Info("Originator will use a gas price of {0} to submit the transaction.", gasPrice); + this.logger.LogInformation("Originator will use a gas price of {0} to submit the transaction.", gasPrice); // Submit the unconfirmed transaction data to the multisig contract, returning a transactionId used to refer to it. // Once sufficient multisig owners have confirmed the transaction the multisig contract will execute it. @@ -489,12 +489,12 @@ private async Task ProcessConversionRequestsAsync() case ConversionRequestStatus.OriginatorSubmitting: { (BigInteger confirmationCount, string blockHash) = await this.ethClientProvider.GetClientForChain(request.DestinationChain).GetConfirmationsAsync(request.ExternalChainTxHash).ConfigureAwait(false); - this.logger.Info($"Originator confirming transaction id '{request.ExternalChainTxHash}' '({request.ExternalChainTxEventId})' before broadcasting; confirmations: {confirmationCount}; Block Hash {blockHash}."); + this.logger.LogInformation($"Originator confirming transaction id '{request.ExternalChainTxHash}' '({request.ExternalChainTxEventId})' before broadcasting; confirmations: {confirmationCount}; Block Hash {blockHash}."); if (confirmationCount < this.SubmissionConfirmationThreshold) break; - this.logger.Info("Originator submitted transaction to multisig in transaction '{0}' and was allocated transactionId '{1}'.", request.ExternalChainTxHash, request.ExternalChainTxEventId); + this.logger.LogInformation("Originator submitted transaction to multisig in transaction '{0}' and was allocated transactionId '{1}'.", request.ExternalChainTxHash, request.ExternalChainTxEventId); this.conversionRequestCoordinationService.AddVote(request.RequestId, BigInteger.Parse(request.ExternalChainTxEventId), this.federationManager.CurrentFederationKey.PubKey); @@ -521,7 +521,7 @@ private async Task ProcessConversionRequestsAsync() if (agreedTransactionId != BigInteger.MinusOne) { - this.logger.Info("Transaction '{0}' has received sufficient votes, it should now start getting confirmed by each peer.", agreedTransactionId); + this.logger.LogInformation("Transaction '{0}' has received sufficient votes, it should now start getting confirmed by each peer.", agreedTransactionId); request.RequestStatus = ConversionRequestStatus.VoteFinalised; } @@ -542,7 +542,7 @@ private async Task ProcessConversionRequestsAsync() if (confirmationCount >= this.interopSettings.GetSettingsByChain(request.DestinationChain).MultisigWalletQuorum) { - this.logger.Info("Transaction '{0}' has received at least {1} confirmations, it will be automatically executed by the multisig contract.", transactionId3, this.interopSettings.GetSettingsByChain(request.DestinationChain).MultisigWalletQuorum); + this.logger.LogInformation("Transaction '{0}' has received at least {1} confirmations, it will be automatically executed by the multisig contract.", transactionId3, this.interopSettings.GetSettingsByChain(request.DestinationChain).MultisigWalletQuorum); request.RequestStatus = ConversionRequestStatus.Processed; request.Processed = true; @@ -552,7 +552,7 @@ private async Task ProcessConversionRequestsAsync() } else { - this.logger.Info("Transaction '{0}' has finished voting but does not yet have {1} confirmations, re-broadcasting votes to peers.", transactionId3, this.interopSettings.GetSettingsByChain(request.DestinationChain).MultisigWalletQuorum); + this.logger.LogInformation("Transaction '{0}' has finished voting but does not yet have {1} confirmations, re-broadcasting votes to peers.", transactionId3, this.interopSettings.GetSettingsByChain(request.DestinationChain).MultisigWalletQuorum); // There are not enough confirmations yet. // Even though the vote is finalised, other nodes may come and go. So we re-broadcast the finalised votes to all federation peers. // Nodes will simply ignore the messages if they are not relevant. @@ -578,7 +578,7 @@ private async Task ProcessConversionRequestsAsync() { // TODO: Should we check the number of confirmations for the submission transaction here too? - this.logger.Info("Quorum reached for conversion transaction '{0}' with transactionId '{1}', submitting confirmation to contract.", request.RequestId, agreedUponId); + this.logger.LogInformation("Quorum reached for conversion transaction '{0}' with transactionId '{1}', submitting confirmation to contract.", request.RequestId, agreedUponId); int gasPrice = this.externalApiPoller.GetGasPrice(); @@ -586,7 +586,7 @@ private async Task ProcessConversionRequestsAsync() if (gasPrice == -1) gasPrice = this.interopSettings.GetSettingsByChain(request.DestinationChain).GasPrice; - this.logger.Info("The non-originator will use a gas price of {0} to confirm the transaction.", gasPrice); + this.logger.LogInformation("The non-originator will use a gas price of {0} to confirm the transaction.", gasPrice); // Once a quorum is reached, each node confirms the agreed transactionId. // If the originator or some other nodes renege on their vote, the current node will not re-confirm a different transactionId. @@ -594,7 +594,7 @@ private async Task ProcessConversionRequestsAsync() request.ExternalChainTxHash = confirmationHash; - this.logger.Info("The hash of the confirmation transaction for conversion transaction '{0}' was '{1}'.", request.RequestId, confirmationHash); + this.logger.LogInformation("The hash of the confirmation transaction for conversion transaction '{0}' was '{1}'.", request.RequestId, confirmationHash); request.RequestStatus = ConversionRequestStatus.VoteFinalised; } @@ -604,7 +604,7 @@ private async Task ProcessConversionRequestsAsync() if (transactionId4 != BigInteger.MinusOne) { - this.logger.Debug("Broadcasting vote (transactionId '{0}') for conversion transaction '{1}'.", transactionId4, request.RequestId); + this.logger.LogDebug("Broadcasting vote (transactionId '{0}') for conversion transaction '{1}'.", transactionId4, request.RequestId); this.conversionRequestCoordinationService.AddVote(request.RequestId, transactionId4, this.federationManager.CurrentFederationKey.PubKey); @@ -661,7 +661,7 @@ private bool DetermineConversionRequestOriginator(int blockHeight, out IFederati // We are not able to simply use the entire federation member list, as only multisig nodes can be transaction originators. List federation = this.federationHistory.GetFederationForBlock(this.chainIndexer.GetHeader(blockHeight)); - this.logger.Info($"Federation retrieved at height '{blockHeight}', size {federation.Count} members."); + this.logger.LogInformation($"Federation retrieved at height '{blockHeight}', size {federation.Count} members."); var multisig = new List(); @@ -702,7 +702,7 @@ private async Task WaitForReplenishmentToBeConfirmedAsync(MultisigTransact return false; (BigInteger confirmationCount, string blockHash) = await this.ethClientProvider.GetClientForChain(destinationChain).GetConfirmationsAsync(identifiers.TransactionHash).ConfigureAwait(false); - this.logger.Info($"[{caller}] Originator confirming transaction id '{identifiers.TransactionHash}' '({identifiers.TransactionId})' before broadcasting; confirmations: {confirmationCount}; Block Hash {blockHash}."); + this.logger.LogInformation($"[{caller}] Originator confirming transaction id '{identifiers.TransactionHash}' '({identifiers.TransactionId})' before broadcasting; confirmations: {confirmationCount}; Block Hash {blockHash}."); if (confirmationCount >= this.SubmissionConfirmationThreshold) break; @@ -732,7 +732,7 @@ private async Task PerformReplenishmentAsync(ConversionRequest request, BigInteg if (originator) { - this.logger.Info("Insufficient reserve balance remaining, initiating mint transaction to replenish reserve."); + this.logger.LogInformation("Insufficient reserve balance remaining, initiating mint transaction to replenish reserve."); // By minting the request amount + the reserve requirement, we cater for arbitrarily large amounts in the request. string mintData = this.ethClientProvider.GetClientForChain(request.DestinationChain).EncodeMintParams(this.interopSettings.GetSettingsByChain(request.DestinationChain).MultisigWalletAddress, amountInWei + this.ReserveBalanceTarget); @@ -743,7 +743,7 @@ private async Task PerformReplenishmentAsync(ConversionRequest request, BigInteg if (gasPrice == -1) gasPrice = this.interopSettings.GetSettingsByChain(request.DestinationChain).GasPrice; - this.logger.Info("Originator will use a gas price of {0} to submit the mint replenishment transaction.", gasPrice); + this.logger.LogInformation("Originator will use a gas price of {0} to submit the mint replenishment transaction.", gasPrice); MultisigTransactionIdentifiers identifiers = await this.ethClientProvider.GetClientForChain(request.DestinationChain).SubmitTransactionAsync(this.interopSettings.GetSettingsByChain(request.DestinationChain).WrappedStraxContractAddress, 0, mintData, gasPrice).ConfigureAwait(false); @@ -759,7 +759,7 @@ private async Task PerformReplenishmentAsync(ConversionRequest request, BigInteg return; } - this.logger.Info("Originator adding its vote for mint transaction id: {0}", mintTransactionId); + this.logger.LogInformation("Originator adding its vote for mint transaction id: {0}", mintTransactionId); this.conversionRequestCoordinationService.AddVote(mintRequestId, mintTransactionId, this.federationManager.CurrentFederationKey.PubKey); @@ -769,7 +769,7 @@ private async Task PerformReplenishmentAsync(ConversionRequest request, BigInteg await this.BroadcastCoordinationVoteRequestAsync(mintRequestId, mintTransactionId, request.DestinationChain).ConfigureAwait(false); } else - this.logger.Info("Insufficient reserve balance remaining, waiting for originator to initiate mint transaction to replenish reserve."); + this.logger.LogInformation("Insufficient reserve balance remaining, waiting for originator to initiate mint transaction to replenish reserve."); BigInteger agreedTransactionId; @@ -783,7 +783,7 @@ private async Task PerformReplenishmentAsync(ConversionRequest request, BigInteg agreedTransactionId = this.conversionRequestCoordinationService.GetAgreedTransactionId(mintRequestId, this.interopSettings.GetSettingsByChain(request.DestinationChain).MultisigWalletQuorum); - this.logger.Debug("Agreed transaction id '{0}'.", agreedTransactionId); + this.logger.LogDebug("Agreed transaction id '{0}'.", agreedTransactionId); if (agreedTransactionId != BigInteger.MinusOne) break; @@ -791,7 +791,7 @@ private async Task PerformReplenishmentAsync(ConversionRequest request, BigInteg // Just re-broadcast. if (originator) { - this.logger.Debug("Originator broadcasting id {0}.", mintTransactionId); + this.logger.LogDebug("Originator broadcasting id {0}.", mintTransactionId); await this.BroadcastCoordinationVoteRequestAsync(mintRequestId, mintTransactionId, request.DestinationChain).ConfigureAwait(false); } @@ -800,7 +800,7 @@ private async Task PerformReplenishmentAsync(ConversionRequest request, BigInteg if (ourTransactionId == BigInteger.MinusOne) ourTransactionId = this.conversionRequestCoordinationService.GetCandidateTransactionId(mintRequestId); - this.logger.Debug("Non-originator broadcasting id {0}.", ourTransactionId); + this.logger.LogDebug("Non-originator broadcasting id {0}.", ourTransactionId); if (ourTransactionId != BigInteger.MinusOne) { @@ -816,7 +816,7 @@ private async Task PerformReplenishmentAsync(ConversionRequest request, BigInteg await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false); } - this.logger.Info("Agreed transaction ID for replenishment transaction: {0}", agreedTransactionId); + this.logger.LogInformation("Agreed transaction ID for replenishment transaction: {0}", agreedTransactionId); if (!originator) { @@ -826,11 +826,11 @@ private async Task PerformReplenishmentAsync(ConversionRequest request, BigInteg if (gasPrice == -1) gasPrice = this.interopSettings.GetSettingsByChain(request.DestinationChain).GasPrice; - this.logger.Info("Non-originator will use a gas price of {0} to confirm the mint replenishment transaction.", gasPrice); + this.logger.LogInformation("Non-originator will use a gas price of {0} to confirm the mint replenishment transaction.", gasPrice); string confirmation = await this.ethClientProvider.GetClientForChain(request.DestinationChain).ConfirmTransactionAsync(agreedTransactionId, gasPrice).ConfigureAwait(false); - this.logger.Info("ID of confirmation transaction: {0}", confirmation); + this.logger.LogInformation("ID of confirmation transaction: {0}", confirmation); } while (true) @@ -840,7 +840,7 @@ private async Task PerformReplenishmentAsync(ConversionRequest request, BigInteg BigInteger confirmationCount = await this.ethClientProvider.GetClientForChain(request.DestinationChain).GetMultisigConfirmationCountAsync(agreedTransactionId).ConfigureAwait(false); - this.logger.Info("Waiting for confirmation of mint replenishment transaction {0}, current count {1}.", mintRequestId, confirmationCount); + this.logger.LogInformation("Waiting for confirmation of mint replenishment transaction {0}, current count {1}.", mintRequestId, confirmationCount); if (confirmationCount >= this.interopSettings.GetSettingsByChain(request.DestinationChain).MultisigWalletQuorum) break; @@ -849,7 +849,7 @@ private async Task PerformReplenishmentAsync(ConversionRequest request, BigInteg await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false); } - this.logger.Info("Mint replenishment transaction {0} fully confirmed.", mintTransactionId); + this.logger.LogInformation("Mint replenishment transaction {0} fully confirmed.", mintTransactionId); while (true) { @@ -860,11 +860,11 @@ private async Task PerformReplenishmentAsync(ConversionRequest request, BigInteg if (balance > startBalance) { - this.logger.Info("The contract's balance has been replenished, new balance {0}.", balance); + this.logger.LogInformation("The contract's balance has been replenished, new balance {0}.", balance); break; } else - this.logger.Info("The contract's balance is unchanged at {0}.", balance); + this.logger.LogInformation("The contract's balance is unchanged at {0}.", balance); await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false); } diff --git a/src/Stratis.Bitcoin.Features.PoA/Collateral/CollateralHeightCommitmentEncoder.cs b/src/Stratis.Bitcoin.Features.PoA/Collateral/CollateralHeightCommitmentEncoder.cs index 2962c88f89..fdf9a0a662 100644 --- a/src/Stratis.Bitcoin.Features.PoA/Collateral/CollateralHeightCommitmentEncoder.cs +++ b/src/Stratis.Bitcoin.Features.PoA/Collateral/CollateralHeightCommitmentEncoder.cs @@ -41,7 +41,7 @@ public byte[] EncodeCommitmentHeight(int height) byte[] commitmentData = null; byte[] magic = null; - this.logger.Debug("Transaction contains {0} OP_RETURN outputs.", opReturnOutputs.Count()); + this.logger.LogDebug("Transaction contains {0} OP_RETURN outputs.", opReturnOutputs.Count()); foreach (Script script in opReturnOutputs) { @@ -56,7 +56,7 @@ public byte[] EncodeCommitmentHeight(int height) if (!correctPrefix) { - this.logger.Debug("Push data contains incorrect prefix for height commitment."); + this.logger.LogDebug("Push data contains incorrect prefix for height commitment."); continue; } diff --git a/src/Stratis.Bitcoin.Features.PoA/FederationManager.cs b/src/Stratis.Bitcoin.Features.PoA/FederationManager.cs index a7ff983d88..c6ff6c8e82 100644 --- a/src/Stratis.Bitcoin.Features.PoA/FederationManager.cs +++ b/src/Stratis.Bitcoin.Features.PoA/FederationManager.cs @@ -103,19 +103,19 @@ public void Initialize() { var genesisFederation = new List(this.network.ConsensusOptions.GenesisFederationMembers); - this.logger.Info("Genesis federation contains {0} members. Their public keys are: {1}", genesisFederation.Count, $"{Environment.NewLine}{string.Join(Environment.NewLine, genesisFederation)}"); + this.logger.LogInformation("Genesis federation contains {0} members. Their public keys are: {1}", genesisFederation.Count, $"{Environment.NewLine}{string.Join(Environment.NewLine, genesisFederation)}"); // Load federation from the db. this.LoadFederation(); if (this.federationMembers == null) { - this.logger.Debug("Federation members are not stored in the database, using genesis federation members."); + this.logger.LogDebug("Federation members are not stored in the database, using genesis federation members."); this.federationMembers = genesisFederation; } // Display federation. - this.logger.Info("Current federation contains {0} members. Their public keys are: {1}", this.federationMembers.Count, Environment.NewLine + string.Join(Environment.NewLine, this.federationMembers)); + this.logger.LogInformation("Current federation contains {0} members. Their public keys are: {1}", this.federationMembers.Count, Environment.NewLine + string.Join(Environment.NewLine, this.federationMembers)); // Set the current federation member's key. if (!InitializeFederationMemberKey()) @@ -124,14 +124,14 @@ public void Initialize() // Loaded key has to be a key for current federation. if (!this.federationMembers.Any(x => x.PubKey == this.CurrentFederationKey.PubKey)) { - this.logger.Warn("Key provided is not registered on the network."); + this.logger.LogWarning("Key provided is not registered on the network."); } // TODO This will be removed once we remove the distinction between FederationMember and CollateralFederationMember if (this.federationMembers.Any(f => f is CollateralFederationMember)) CheckCollateralMembers(); - this.logger.Info("Federation key pair was successfully loaded. Your public key is: '{0}'.", this.CurrentFederationKey.PubKey); + this.logger.LogInformation("Federation key pair was successfully loaded. Your public key is: '{0}'.", this.CurrentFederationKey.PubKey); } private bool InitializeFederationMemberKey() @@ -142,7 +142,7 @@ private bool InitializeFederationMemberKey() Key key = new KeyTool(this.nodeSettings.DataFolder).LoadPrivateKey(); if (key == null) { - this.logger.Warn("No federation key was loaded from 'federationKey.dat'."); + this.logger.LogWarning("No federation key was loaded from 'federationKey.dat'."); return false; } @@ -151,7 +151,7 @@ private bool InitializeFederationMemberKey() if (this.CurrentFederationKey == null) { - this.logger.Trace("(-)[NOT_FED_MEMBER]"); + this.logger.LogTrace("(-)[NOT_FED_MEMBER]"); return false; } @@ -296,13 +296,13 @@ private void AddFederationMemberLocked(IFederationMember federationMember) { if (this.federationMembers.IsCollateralAddressRegistered(collateralFederationMember.CollateralMainchainAddress)) { - this.logger.Trace("(-)[DUPLICATED_COLLATERAL_ADDR]"); + this.logger.LogTrace("(-)[DUPLICATED_COLLATERAL_ADDR]"); return; } if (this.federationMembers.Contains(federationMember)) { - this.logger.Trace("(-)[ALREADY_EXISTS]"); + this.logger.LogTrace("(-)[ALREADY_EXISTS]"); return; } } @@ -311,7 +311,7 @@ private void AddFederationMemberLocked(IFederationMember federationMember) this.SetIsFederationMember(); - this.logger.Info("Federation member '{0}' was added.", federationMember); + this.logger.LogInformation("Federation member '{0}' was added.", federationMember); } public void RemoveFederationMember(IFederationMember federationMember) @@ -322,7 +322,7 @@ public void RemoveFederationMember(IFederationMember federationMember) this.SetIsFederationMember(); - this.logger.Info("Federation member '{0}' was removed.", federationMember); + this.logger.LogInformation("Federation member '{0}' was removed.", federationMember); } this.signals.Publish(new FedMemberKicked(federationMember)); diff --git a/src/Stratis.Bitcoin.Features.PoA/Voting/FederationController.cs b/src/Stratis.Bitcoin.Features.PoA/Voting/FederationController.cs index b8cc82512e..9a225a77c5 100644 --- a/src/Stratis.Bitcoin.Features.PoA/Voting/FederationController.cs +++ b/src/Stratis.Bitcoin.Features.PoA/Voting/FederationController.cs @@ -66,7 +66,7 @@ public IActionResult Reconstruct() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -142,7 +142,7 @@ public IActionResult GetCurrentMemberInfo() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -182,7 +182,7 @@ public IActionResult GetMembers() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -209,7 +209,7 @@ public IActionResult GetPubkeyAtHeight([FromQuery(Name = "blockHeight")] int blo } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -242,7 +242,7 @@ public IActionResult GetFederationAtHeight([FromQuery(Name = "blockHeight")] int } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } diff --git a/src/Stratis.Bitcoin.Features.PoA/Voting/JoinFederationRequestEncoder.cs b/src/Stratis.Bitcoin.Features.PoA/Voting/JoinFederationRequestEncoder.cs index 7f5ef091f0..c72aa1d5d3 100644 --- a/src/Stratis.Bitcoin.Features.PoA/Voting/JoinFederationRequestEncoder.cs +++ b/src/Stratis.Bitcoin.Features.PoA/Voting/JoinFederationRequestEncoder.cs @@ -60,7 +60,7 @@ public JoinFederationRequest Decode(byte[] votingRequestDataBytes) if (deserializeStream.ProcessedBytes != votingRequestDataBytes.Length) { - this.logger.Trace("(-)[INVALID_SIZE]"); + this.logger.LogTrace("(-)[INVALID_SIZE]"); PoAConsensusErrors.VotingRequestInvalidFormat.Throw(); } @@ -69,8 +69,8 @@ public JoinFederationRequest Decode(byte[] votingRequestDataBytes) } catch (Exception e) { - this.logger.Debug("Exception during deserialization: '{0}'.", e.ToString()); - this.logger.Trace("(-)[DESERIALIZING_EXCEPTION]"); + this.logger.LogDebug("Exception during deserialization: '{0}'.", e.ToString()); + this.logger.LogTrace("(-)[DESERIALIZING_EXCEPTION]"); PoAConsensusErrors.VotingRequestInvalidFormat.Throw(); return null; diff --git a/src/Stratis.Bitcoin.Features.PoA/Voting/PollsCollection.cs b/src/Stratis.Bitcoin.Features.PoA/Voting/PollsCollection.cs index 5100dfe46e..209d61253c 100644 --- a/src/Stratis.Bitcoin.Features.PoA/Voting/PollsCollection.cs +++ b/src/Stratis.Bitcoin.Features.PoA/Voting/PollsCollection.cs @@ -40,7 +40,7 @@ public void Add(Poll poll) { if (this.polls.Contains(poll)) { - this.logger.Warn("The poll already exists: '{0}'.", poll); + this.logger.LogWarning("The poll already exists: '{0}'.", poll); return; } diff --git a/src/Stratis.Bitcoin.Features.PoA/Voting/PollsRepository.cs b/src/Stratis.Bitcoin.Features.PoA/Voting/PollsRepository.cs index 3dd2ba24ec..000a263c9e 100644 --- a/src/Stratis.Bitcoin.Features.PoA/Voting/PollsRepository.cs +++ b/src/Stratis.Bitcoin.Features.PoA/Voting/PollsRepository.cs @@ -66,7 +66,7 @@ public void Initialize() var uniquePolls = new HashSet(polls); if (uniquePolls.Count != polls.Count) { - this.logger.Warn("The polls repository contains {0} duplicate polls, it will be rebuilt.", polls.Count - uniquePolls.Count); + this.logger.LogWarning("The polls repository contains {0} duplicate polls, it will be rebuilt.", polls.Count - uniquePolls.Count); this.ResetLocked(transaction); transaction.Commit(); @@ -77,7 +77,7 @@ public void Initialize() Row rowTip = transaction.Select(DataTable, RepositoryTipKey); if (!rowTip.Exists) { - this.logger.Info("The polls repository tip is unknown, it will be rebuilt."); + this.logger.LogInformation("The polls repository tip is unknown, it will be rebuilt."); this.ResetLocked(transaction); transaction.Commit(); return; @@ -90,11 +90,11 @@ public void Initialize() if (chainedHeaderTip != null) { this.highestPollId = (polls.Count > 0) ? polls.Max(p => p.Id) : -1; - this.logger.Info("Polls repository tip exists on chain; initializing at height {0}; highest poll id: {1}.", this.CurrentTip.Height, this.highestPollId); + this.logger.LogInformation("Polls repository tip exists on chain; initializing at height {0}; highest poll id: {1}.", this.CurrentTip.Height, this.highestPollId); return; } - this.logger.Info("The polls repository tip {0} was not found in the consensus chain, determining fork.", this.CurrentTip); + this.logger.LogInformation("The polls repository tip {0} was not found in the consensus chain, determining fork.", this.CurrentTip); // The polls repository tip could not be found in the chain. // Look at all other known hash/height pairs to find something in common with the consensus chain. @@ -112,7 +112,7 @@ public void Initialize() if (maxGoodHeight == -1) { - this.logger.Info("No common blocks found; the repo will be rebuilt from scratch."); + this.logger.LogInformation("No common blocks found; the repo will be rebuilt from scratch."); this.ResetLocked(transaction); transaction.Commit(); return; @@ -120,7 +120,7 @@ public void Initialize() this.CurrentTip = new HashHeightPair(this.chainIndexer.GetHeader(maxGoodHeight)); - this.logger.Info("Common block found at height {0}; the repo will be rebuilt from there.", this.CurrentTip.Height); + this.logger.LogInformation("Common block found at height {0}; the repo will be rebuilt from there.", this.CurrentTip.Height); // Trim polls to tip. HashSet pollsToDelete = new HashSet(); @@ -129,7 +129,7 @@ public void Initialize() if (poll.PollStartBlockData.Height > this.CurrentTip.Height) { pollsToDelete.Add(poll); - this.logger.Debug("Poll {0} will be deleted.", poll.Id); + this.logger.LogDebug("Poll {0} will be deleted.", poll.Id); continue; } @@ -157,7 +157,7 @@ public void Initialize() // if so un-expire it. if (poll.IsExpired && !IsPollExpiredAt(poll, chainedHeaderTip, this.network)) { - this.logger.Debug("Un-expiring poll {0}.", poll.Id); + this.logger.LogDebug("Un-expiring poll {0}.", poll.Id); poll.IsExpired = false; modified = true; @@ -171,11 +171,11 @@ public void Initialize() SaveCurrentTip(transaction, this.CurrentTip); transaction.Commit(); - this.logger.Info("Polls repository initialized at height {0}; highest poll id: {1}.", this.CurrentTip.Height, this.highestPollId); + this.logger.LogInformation("Polls repository initialized at height {0}; highest poll id: {1}.", this.CurrentTip.Height, this.highestPollId); } catch (Exception err) when (err.Message == "No more byte to read") { - this.logger.Warn("There was an error reading the polls repository, it will be rebuild."); + this.logger.LogWarning("There was an error reading the polls repository, it will be rebuild."); this.ResetLocked(transaction); transaction.Commit(); } diff --git a/src/Stratis.Bitcoin.Features.PoA/Voting/VotingController.cs b/src/Stratis.Bitcoin.Features.PoA/Voting/VotingController.cs index 41a55202ac..ea700e1ed5 100644 --- a/src/Stratis.Bitcoin.Features.PoA/Voting/VotingController.cs +++ b/src/Stratis.Bitcoin.Features.PoA/Voting/VotingController.cs @@ -73,7 +73,7 @@ public IActionResult GetPollsRepositoryTip() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -104,7 +104,7 @@ public IActionResult GetPendingPolls([FromQuery] VoteKey voteType, [FromQuery] s } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -135,7 +135,7 @@ public IActionResult GetFinishedPolls([FromQuery] VoteKey voteType, [FromQuery] } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -166,7 +166,7 @@ public IActionResult GetExecutedPolls([FromQuery] VoteKey voteType, [FromQuery] } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -192,7 +192,7 @@ public IActionResult GetExpiredPollsMembers() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -218,7 +218,7 @@ public IActionResult GetExpiredPollsWhitelist() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -243,7 +243,7 @@ public IActionResult GetWhitelistedHashes() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -308,7 +308,7 @@ private IActionResult VoteWhitelistRemoveHashMember(HashModel request, bool whit } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "There was a problem executing a command.", e.ToString()); } } @@ -335,7 +335,7 @@ public IActionResult GetScheduledVotes() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -386,7 +386,7 @@ public IActionResult VoteKickFederationMember([FromBody] KickFederationMemberMod } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "There was a problem executing a vote to be scheduled.", e.ToString()); } } diff --git a/src/Stratis.Bitcoin.Features.PoA/Voting/VotingDataEncoder.cs b/src/Stratis.Bitcoin.Features.PoA/Voting/VotingDataEncoder.cs index 4a58fd42c2..9dabf40952 100644 --- a/src/Stratis.Bitcoin.Features.PoA/Voting/VotingDataEncoder.cs +++ b/src/Stratis.Bitcoin.Features.PoA/Voting/VotingDataEncoder.cs @@ -30,7 +30,7 @@ public List Decode(byte[] votingDataBytes) { if (votingDataBytes.Length > VotingDataMaxSerializedSize) { - this.logger.Trace("(-)[INVALID_SIZE]"); + this.logger.LogTrace("(-)[INVALID_SIZE]"); PoAConsensusErrors.VotingDataInvalidFormat.Throw(); } @@ -47,8 +47,8 @@ public List Decode(byte[] votingDataBytes) } catch (Exception e) { - this.logger.Debug("Exception during deserialization: '{0}'.", e.ToString()); - this.logger.Trace("(-)[DESERIALIZING_EXCEPTION]"); + this.logger.LogDebug("Exception during deserialization: '{0}'.", e.ToString()); + this.logger.LogTrace("(-)[DESERIALIZING_EXCEPTION]"); PoAConsensusErrors.VotingDataInvalidFormat.Throw(); return null; @@ -94,7 +94,7 @@ public byte[] ExtractRawVotingData(Transaction tx) if (votingData != null) { - this.logger.Trace("(-)[TOO_MANY_VOTING_OUTPUTS]"); + this.logger.LogTrace("(-)[TOO_MANY_VOTING_OUTPUTS]"); PoAConsensusErrors.TooManyVotingOutputs.Throw(); } diff --git a/src/Stratis.Bitcoin.Features.PoA/Voting/VotingManager.cs b/src/Stratis.Bitcoin.Features.PoA/Voting/VotingManager.cs index 7b61421395..712e9ce3dd 100644 --- a/src/Stratis.Bitcoin.Features.PoA/Voting/VotingManager.cs +++ b/src/Stratis.Bitcoin.Features.PoA/Voting/VotingManager.cs @@ -114,7 +114,7 @@ public void Initialize(IFederationHistory federationHistory, IIdleFederationMemb this.isInitialized = true; - this.logger.Debug("VotingManager initialized."); + this.logger.LogDebug("VotingManager initialized."); } /// Schedules a vote for the next time when the block will be mined. @@ -126,7 +126,7 @@ public void ScheduleVote(VotingData votingData) if (!this.federationManager.IsFederationMember) { - this.logger.Trace("(-)[NOT_FED_MEMBER]"); + this.logger.LogTrace("(-)[NOT_FED_MEMBER]"); throw new InvalidOperationException("Not a federation member!"); } @@ -138,7 +138,7 @@ public void ScheduleVote(VotingData votingData) this.SanitizeScheduledPollsLocked(); } - this.logger.Debug("Vote was scheduled with key: {0}.", votingData.Key); + this.logger.LogDebug("Vote was scheduled with key: {0}.", votingData.Key); } /// Provides a copy of scheduled voting data. @@ -171,7 +171,7 @@ public List GetAndCleanScheduledVotes() this.scheduledVotingData = new List(); if (votingData.Count > 0) - this.logger.Debug("{0} scheduled votes were taken.", votingData.Count); + this.logger.LogDebug("{0} scheduled votes were taken.", votingData.Count); return votingData; } @@ -316,7 +316,7 @@ public List GetFederationFromExecutedPolls() { if (federationMember is CollateralFederationMember colMember2 && federation.IsCollateralAddressRegistered(colMember2.CollateralMainchainAddress)) { - this.logger.Debug("Not adding member '{0}' with duplicate collateral address '{1}'.", federationMember.PubKey.ToHex(), colMember2.CollateralMainchainAddress); + this.logger.LogDebug("Not adding member '{0}' with duplicate collateral address '{1}'.", federationMember.PubKey.ToHex(), colMember2.CollateralMainchainAddress); continue; } @@ -414,7 +414,7 @@ public List GetModifiedFederation(ChainedHeader chainedHeader { if (modifiedFederation.IsCollateralAddressRegistered(collateralFederationMember.CollateralMainchainAddress)) { - this.logger.Debug("Not adding member '{0}' with duplicate collateral address '{1}'.", collateralFederationMember.PubKey.ToHex(), collateralFederationMember.CollateralMainchainAddress); + this.logger.LogDebug("Not adding member '{0}' with duplicate collateral address '{1}'.", collateralFederationMember.PubKey.ToHex(), collateralFederationMember.CollateralMainchainAddress); continue; } @@ -476,7 +476,7 @@ private void ProcessBlock(DBreeze.Transactions.Transaction transaction, ChainedH foreach (Poll poll in this.GetPendingPolls().Where(p => PollsRepository.IsPollExpiredAt(p, chBlock.ChainedHeader, this.network as PoANetwork)).ToList()) { - this.logger.Debug("Expiring poll '{0}'.", poll); + this.logger.LogDebug("Expiring poll '{0}'.", poll); // Flag the poll as expired. The "PollVotedInFavorBlockData" will always be null at this point due to the "GetPendingPolls" filter above. // The value of the hash is not significant but we set it to a non-zero value to prevent the field from being de-serialized as null. @@ -491,7 +491,7 @@ private void ProcessBlock(DBreeze.Transactions.Transaction transaction, ChainedH if (poll.IsExpired || chBlock.ChainedHeader.Height != (poll.PollVotedInFavorBlockData.Height + this.network.Consensus.MaxReorgLength)) continue; - this.logger.Debug("Applying poll '{0}'.", poll); + this.logger.LogDebug("Applying poll '{0}'.", poll); this.pollResultExecutor.ApplyChange(poll.VotingData); poll.PollExecutedBlockData = new HashHeightPair(chBlock.ChainedHeader); @@ -514,8 +514,8 @@ private void ProcessBlock(DBreeze.Transactions.Transaction transaction, ChainedH IFederationMember member = this.federationHistory.GetFederationMemberForBlock(chBlock.ChainedHeader); if (member == null) { - this.logger.Error("The block was mined by a non-federation-member!"); - this.logger.Trace("(-)[ALIEN_BLOCK]"); + this.logger.LogError("The block was mined by a non-federation-member!"); + this.logger.LogTrace("(-)[ALIEN_BLOCK]"); this.PollsRepository.SaveCurrentTip(pollsRepositoryModified ? transaction : null, chBlock.ChainedHeader); return; @@ -527,7 +527,7 @@ private void ProcessBlock(DBreeze.Transactions.Transaction transaction, ChainedH List votingDataList = this.votingDataEncoder.Decode(rawVotingData); - this.logger.Debug("Applying {0} voting data items included in a block by '{1}'.", votingDataList.Count, fedMemberKeyHex); + this.logger.LogDebug("Applying {0} voting data items included in a block by '{1}'.", votingDataList.Count, fedMemberKeyHex); lock (this.locker) { @@ -566,7 +566,7 @@ private void ProcessBlock(DBreeze.Transactions.Transaction transaction, ChainedH this.PollsRepository.AddPolls(transaction, poll); pollsRepositoryModified = true; - this.logger.Debug("New poll was created: '{0}'.", poll); + this.logger.LogDebug("New poll was created: '{0}'.", poll); }); } else if (!poll.PubKeysHexVotedInFavor.Any(v => v.PubKey == fedMemberKeyHex)) @@ -575,11 +575,11 @@ private void ProcessBlock(DBreeze.Transactions.Transaction transaction, ChainedH this.PollsRepository.UpdatePoll(transaction, poll); pollsRepositoryModified = true; - this.logger.Debug("Voted on existing poll: '{0}'.", poll); + this.logger.LogDebug("Voted on existing poll: '{0}'.", poll); } else { - this.logger.Debug("Fed member '{0}' already voted for this poll. Ignoring his vote. Poll: '{1}'.", fedMemberKeyHex, poll); + this.logger.LogDebug("Fed member '{0}' already voted for this poll. Ignoring his vote. Poll: '{1}'.", fedMemberKeyHex, poll); } List modifiedFederation = this.federationManager.GetFederationMembers(); @@ -596,7 +596,7 @@ private void ProcessBlock(DBreeze.Transactions.Transaction transaction, ChainedH chainedHeader = this.chainIndexer.GetHeader(poll.PollStartBlockData.Hash); if (chainedHeader == null) { - this.logger.Warn("Couldn't retrieve header for block at height-hash: {0}-{1}.", poll.PollStartBlockData.Height, poll.PollStartBlockData.Hash?.ToString()); + this.logger.LogWarning("Couldn't retrieve header for block at height-hash: {0}-{1}.", poll.PollStartBlockData.Height, poll.PollStartBlockData.Hash?.ToString()); Guard.NotNull(chainedHeader, nameof(chainedHeader)); Guard.NotNull(chainedHeader.Header, nameof(chainedHeader.Header)); @@ -618,7 +618,7 @@ private void ProcessBlock(DBreeze.Transactions.Transaction transaction, ChainedH int requiredVotesCount = (fedMembersHex.Count / 2) + 1; - this.logger.Debug("Fed members count: {0}, valid votes count: {1}, required votes count: {2}.", fedMembersHex.Count, validVotesCount, requiredVotesCount); + this.logger.LogDebug("Fed members count: {0}, valid votes count: {1}, required votes count: {2}.", fedMembersHex.Count, validVotesCount, requiredVotesCount); if (validVotesCount < requiredVotesCount) continue; @@ -636,7 +636,7 @@ private void ProcessBlock(DBreeze.Transactions.Transaction transaction, ChainedH } catch (Exception ex) { - this.logger.Error(ex, ex.ToString()); + this.logger.LogError(ex, ex.ToString()); throw; } finally @@ -656,7 +656,7 @@ private void UnProcessBlock(DBreeze.Transactions.Transaction transaction, Chaine { foreach (Poll poll in this.polls.Where(x => !x.IsPending && x.PollExecutedBlockData?.Hash == chBlock.ChainedHeader.HashBlock).ToList()) { - this.logger.Debug("Reverting poll execution '{0}'.", poll); + this.logger.LogDebug("Reverting poll execution '{0}'.", poll); this.pollResultExecutor.RevertChange(poll.VotingData); poll.PollExecutedBlockData = null; @@ -666,7 +666,7 @@ private void UnProcessBlock(DBreeze.Transactions.Transaction transaction, Chaine foreach (Poll poll in this.polls.Where(x => x.IsExpired && !PollsRepository.IsPollExpiredAt(x, chBlock.ChainedHeader.Previous, this.network as PoANetwork)).ToList()) { - this.logger.Debug("Reverting poll expiry '{0}'.", poll); + this.logger.LogDebug("Reverting poll expiry '{0}'.", poll); // Revert back to null as this field would have been when the poll was expired. poll.IsExpired = false; @@ -683,7 +683,7 @@ private void UnProcessBlock(DBreeze.Transactions.Transaction transaction, Chaine if (rawVotingData == null) { - this.logger.Trace("(-)[NO_VOTING_DATA]"); + this.logger.LogTrace("(-)[NO_VOTING_DATA]"); this.PollsRepository.SaveCurrentTip(pollsRepositoryModified ? transaction : null, chBlock.ChainedHeader.Previous); return; @@ -708,7 +708,7 @@ private void UnProcessBlock(DBreeze.Transactions.Transaction transaction, Chaine targetPoll = this.polls.Last(x => x.VotingData == votingData); } - this.logger.Debug("Reverting poll voting in favor: '{0}'.", targetPoll); + this.logger.LogDebug("Reverting poll voting in favor: '{0}'.", targetPoll); if (targetPoll.PollVotedInFavorBlockData == new HashHeightPair(chBlock.ChainedHeader)) { @@ -732,7 +732,7 @@ private void UnProcessBlock(DBreeze.Transactions.Transaction transaction, Chaine this.PollsRepository.RemovePolls(transaction, targetPoll.Id); pollsRepositoryModified = true; - this.logger.Debug("Poll with Id {0} was removed.", targetPoll.Id); + this.logger.LogDebug("Poll with Id {0} was removed.", targetPoll.Id); } } } @@ -819,7 +819,7 @@ internal bool Synchronize(ChainedHeader newTip) { if (this.nodeLifetime.ApplicationStopping.IsCancellationRequested) { - this.logger.Trace("(-)[NODE_DISPOSED]"); + this.logger.LogTrace("(-)[NODE_DISPOSED]"); this.PollsRepository.SaveCurrentTip(currentTransaction); currentTransaction.Commit(); currentTransaction.Dispose(); @@ -837,7 +837,7 @@ internal bool Synchronize(ChainedHeader newTip) var progress = (int)((decimal)header.Height / this.chainIndexer.Tip.Height * 100); var progressString = $"Synchronizing voting data at height {header.Height} / {this.chainIndexer.Tip.Height} ({progress} %)."; - this.logger.Info(progressString); + this.logger.LogInformation(progressString); this.signals.Publish(new FullNodeEvent() { Message = progressString, State = FullNodeState.Initializing.ToString() }); this.PollsRepository.SaveCurrentTip(currentTransaction); diff --git a/src/Stratis.Bitcoin.Features.SignalR/EventSubscriptionService.cs b/src/Stratis.Bitcoin.Features.SignalR/EventSubscriptionService.cs index 0b9e8b31c3..b5c0ea48cb 100644 --- a/src/Stratis.Bitcoin.Features.SignalR/EventSubscriptionService.cs +++ b/src/Stratis.Bitcoin.Features.SignalR/EventSubscriptionService.cs @@ -36,7 +36,7 @@ public void Init() { foreach (IClientEvent eventToHandle in this.options.EventsToHandle) { - this.logger.Debug("Create subscription for {0}", eventToHandle.NodeEventType); + this.logger.LogDebug("Create subscription for {0}", eventToHandle.NodeEventType); async Task callback(EventBase eventBase) { diff --git a/src/Stratis.Bitcoin.Features.SignalR/EventsHub.cs b/src/Stratis.Bitcoin.Features.SignalR/EventsHub.cs index eb04fc3b4d..dfce4fa0df 100644 --- a/src/Stratis.Bitcoin.Features.SignalR/EventsHub.cs +++ b/src/Stratis.Bitcoin.Features.SignalR/EventsHub.cs @@ -34,13 +34,13 @@ public EventsHub() public override Task OnConnectedAsync() { - this.logger.Debug("New client with id {id} connected", this.Context.ConnectionId); + this.logger.LogDebug("New client with id {id} connected", this.Context.ConnectionId); return base.OnConnectedAsync(); } public override Task OnDisconnectedAsync(Exception exception) { - this.logger.Debug("Client with id {id} disconnected", this.Context.ConnectionId); + this.logger.LogDebug("Client with id {id} disconnected", this.Context.ConnectionId); return base.OnDisconnectedAsync(exception); } @@ -60,7 +60,7 @@ public void SendMessage(SignalRMessageArgs message) } catch (Exception e) { - this.logger.Error("Error SendMessage", e); + this.logger.LogError("Error SendMessage", e); } } @@ -94,7 +94,7 @@ public async Task SendToClientsAsync(IClientEvent @event) } catch (Exception ex) { - this.logger.Error(ex, "Error sending to clients"); + this.logger.LogError(ex, "Error sending to clients"); } } } diff --git a/src/Stratis.Bitcoin.Features.SmartContracts/Wallet/SmartContractWalletFeature.cs b/src/Stratis.Bitcoin.Features.SmartContracts/Wallet/SmartContractWalletFeature.cs index ba02cb090a..f7bd563423 100644 --- a/src/Stratis.Bitcoin.Features.SmartContracts/Wallet/SmartContractWalletFeature.cs +++ b/src/Stratis.Bitcoin.Features.SmartContracts/Wallet/SmartContractWalletFeature.cs @@ -27,7 +27,7 @@ public override Task InitializeAsync() { ILogger logger = LogManager.GetCurrentClassLogger(); - logger.Info("Smart Contract Feature Wallet Injected."); + logger.LogInformation("Smart Contract Feature Wallet Injected."); return Task.CompletedTask; } diff --git a/src/Stratis.Bitcoin/Base/ChainRepository.cs b/src/Stratis.Bitcoin/Base/ChainRepository.cs index d0b5de5e76..ea64f7c9bf 100644 --- a/src/Stratis.Bitcoin/Base/ChainRepository.cs +++ b/src/Stratis.Bitcoin/Base/ChainRepository.cs @@ -72,7 +72,7 @@ public Task LoadAsync(ChainedHeader genesisHeader) if (this.signals != null) this.signals.Publish(new FullNodeEvent() { Message = $"Loading chain at height {height}.", State = FullNodeState.Initializing.ToString() }); - this.logger.Info($"Loading chain at height {height}."); + this.logger.LogInformation($"Loading chain at height {height}."); } height++; diff --git a/src/Stratis.Bitcoin/BlockPulling/BlockPuller.cs b/src/Stratis.Bitcoin/BlockPulling/BlockPuller.cs index d92040b31f..790e290ee5 100644 --- a/src/Stratis.Bitcoin/BlockPulling/BlockPuller.cs +++ b/src/Stratis.Bitcoin/BlockPulling/BlockPuller.cs @@ -272,7 +272,7 @@ public void RequestPeerServices(NetworkPeerServices services) if ((peer == null) || !this.networkPeerRequirement.Check(peer.PeerVersion, peer.Inbound, out reason)) { - this.logger.Debug("Peer Id {0} does not meet requirements, reason: {1}", peerIdToBehavior.Key, reason); + this.logger.LogDebug("Peer Id {0} does not meet requirements, reason: {1}", peerIdToBehavior.Key, reason); peerIdsToRemove.Add(peerIdToBehavior.Key); } } @@ -325,7 +325,7 @@ public void NewPeerTipClaimed(INetworkPeer peer, ChainedHeader newTip) if (this.pullerBehaviorsByPeerId.TryGetValue(peerId, out IBlockPullerBehavior behavior)) { behavior.Tip = newTip; - this.logger.Debug("Tip for peer with ID {0} was changed to '{1}'.", peerId, newTip); + this.logger.LogDebug("Tip for peer with ID {0} was changed to '{1}'.", peerId, newTip); } else { @@ -337,10 +337,10 @@ public void NewPeerTipClaimed(INetworkPeer peer, ChainedHeader newTip) behavior.Tip = newTip; this.pullerBehaviorsByPeerId.Add(peerId, behavior); - this.logger.Debug("New peer with ID {0} and tip '{1}' was added.", peerId, newTip); + this.logger.LogDebug("New peer with ID {0} and tip '{1}' was added.", peerId, newTip); } else - this.logger.Debug("Peer ID {0} was discarded since he doesn't support the requirements, reason: {1}", peerId, reason); + this.logger.LogDebug("Peer ID {0} was discarded since he doesn't support the requirements, reason: {1}", peerId, reason); } } } @@ -374,7 +374,7 @@ public void RequestBlocksDownload(List headers, bool highPriority Id = jobId }); - this.logger.Debug("{0} blocks were requested from puller. Job ID {1} was created.", headers.Count, jobId); + this.logger.LogDebug("{0} blocks were requested from puller. Job ID {1} was created.", headers.Count, jobId); this.processQueuesSignal.Set(); } @@ -391,7 +391,7 @@ private async Task AssignerLoopAsync() } catch (OperationCanceledException) { - this.logger.Trace("(-)[CANCELLED]"); + this.logger.LogTrace("(-)[CANCELLED]"); return; } @@ -410,7 +410,7 @@ private async Task StallingLoopAsync() } catch (OperationCanceledException) { - this.logger.Trace("(-)[CANCELLED]"); + this.logger.LogTrace("(-)[CANCELLED]"); return; } @@ -441,27 +441,27 @@ private async Task AssignDownloadJobsAsync() if (emptySlots >= slotsThreshold) this.ProcessQueueLocked(this.downloadJobsQueue, newAssignments, failedHashes, emptySlots); else - this.logger.Debug("Slots threshold is not met, queue will not be processed. There are {0} empty slots, threshold is {1}.", emptySlots, slotsThreshold); + this.logger.LogDebug("Slots threshold is not met, queue will not be processed. There are {0} empty slots, threshold is {1}.", emptySlots, slotsThreshold); this.processQueuesSignal.Reset(); } if (newAssignments.Count != 0) { - this.logger.Debug("Total amount of downloads assigned in this iteration is {0}.", newAssignments.Count); + this.logger.LogDebug("Total amount of downloads assigned in this iteration is {0}.", newAssignments.Count); await this.AskPeersForBlocksAsync(newAssignments).ConfigureAwait(false); } // Call callbacks with null since puller failed to deliver requested blocks. if (failedHashes.Count != 0) - this.logger.Debug("{0} jobs partially or fully failed.", failedHashes.Count); + this.logger.LogDebug("{0} jobs partially or fully failed.", failedHashes.Count); foreach (uint256 failedJob in failedHashes) { // Avoid calling callbacks on shutdown. if (this.cancellationSource.IsCancellationRequested) { - this.logger.Debug("Callbacks won't be called because component is being disposed."); + this.logger.LogDebug("Callbacks won't be called because component is being disposed."); break; } @@ -487,7 +487,7 @@ private void ProcessQueueLocked(Queue jobsQueue, List assignments) if (!success) { - this.logger.Debug("Failed to ask peer {0} for {1} blocks.", peerId, hashes.Count); + this.logger.LogDebug("Failed to ask peer {0} for {1} blocks.", peerId, hashes.Count); this.PeerDisconnected(peerId); } } @@ -637,7 +637,7 @@ private List DistributeHeadersLocked(DownloadJob downloadJob, if (peerBehaviors.Count == 0) { - this.logger.Debug("There are no peers that can participate in download job distribution! Job ID {0} failed.", downloadJob.Id); + this.logger.LogDebug("There are no peers that can participate in download job distribution! Job ID {0} failed.", downloadJob.Id); jobFailed = true; } @@ -683,7 +683,7 @@ private List DistributeHeadersLocked(DownloadJob downloadJob, lastSucceededIndex = index; - this.logger.Debug("Block '{0}' was assigned to peer ID {1}.", header.HashBlock, peerId); + this.logger.LogDebug("Block '{0}' was assigned to peer ID {1}.", header.HashBlock, peerId); break; } else @@ -695,7 +695,7 @@ private List DistributeHeadersLocked(DownloadJob downloadJob, continue; jobFailed = true; - this.logger.Debug("Job {0} failed because there is no peer claiming header '{1}'.", downloadJob.Id, header); + this.logger.LogDebug("Job {0} failed because there is no peer claiming header '{1}'.", downloadJob.Id, header); } } } @@ -721,7 +721,7 @@ private List DistributeHeadersLocked(DownloadJob downloadJob, private void CheckStalling() { int lastImportantHeight = this.chainState.ConsensusTip.Height + ImportantHeightMargin; - this.logger.Debug("Blocks up to height {0} are considered to be important.", lastImportantHeight); + this.logger.LogDebug("Blocks up to height {0} are considered to be important.", lastImportantHeight); var allReleasedAssignments = new List>>(); @@ -755,7 +755,7 @@ private void CheckStalling() int assignedCount = this.assignedHeadersByPeerId[peerId].Count; - this.logger.Debug("Peer {0} failed to deliver {1} blocks from which some were important.", peerId, assignedCount); + this.logger.LogDebug("Peer {0} failed to deliver {1} blocks from which some were important.", peerId, assignedCount); lock (this.peerLock) { @@ -797,15 +797,15 @@ public void PushBlock(uint256 blockHash, Block block, int peerId) { if (!this.assignedDownloadsByHash.TryGetValue(blockHash, out assignedDownload)) { - this.logger.Trace("(-)[BLOCK_NOT_REQUESTED]"); + this.logger.LogTrace("(-)[BLOCK_NOT_REQUESTED]"); return; } - this.logger.Debug("Assignment '{0}' for peer ID {1} was delivered by peer ID {2}.", blockHash, assignedDownload.PeerId, peerId); + this.logger.LogDebug("Assignment '{0}' for peer ID {1} was delivered by peer ID {2}.", blockHash, assignedDownload.PeerId, peerId); if (assignedDownload.PeerId != peerId) { - this.logger.Trace("(-)[WRONG_PEER_DELIVERED]"); + this.logger.LogTrace("(-)[WRONG_PEER_DELIVERED]"); return; } @@ -813,7 +813,7 @@ public void PushBlock(uint256 blockHash, Block block, int peerId) } double deliveredInSeconds = (this.dateTimeProvider.GetUtcNow() - assignedDownload.AssignedTime).TotalSeconds; - this.logger.Debug("Peer {0} delivered block '{1}' in {2} seconds.", assignedDownload.PeerId, blockHash, deliveredInSeconds); + this.logger.LogDebug("Peer {0} delivered block '{1}' in {2} seconds.", assignedDownload.PeerId, blockHash, deliveredInSeconds); lock (this.peerLock) { @@ -859,7 +859,7 @@ private void RecalculateQualityScoreLocked(IBlockPullerBehavior pullerBehavior, } else { - this.logger.Debug("Peer ID {0} is the fastest peer. Recalculating quality score of all peers.", peerId); + this.logger.LogDebug("Peer ID {0} is the fastest peer. Recalculating quality score of all peers.", peerId); // This is the best peer. Recalculate quality score for everyone. foreach (IBlockPullerBehavior peerPullerBehavior in this.pullerBehaviorsByPeerId.Values) @@ -881,7 +881,7 @@ private void RecalculateMaxBlocksBeingDownloadedLocked() if (this.maxBlocksBeingDownloaded < MinimalCountOfBlocksBeingDownloaded) this.maxBlocksBeingDownloaded = MinimalCountOfBlocksBeingDownloaded; - this.logger.Debug("Max number of blocks that can be downloaded at the same time is set to {0}.", this.maxBlocksBeingDownloaded); + this.logger.LogDebug("Max number of blocks that can be downloaded at the same time is set to {0}.", this.maxBlocksBeingDownloaded); } /// @@ -932,7 +932,7 @@ private Dictionary> ReleaseAssignmentsLocked(int peerId assignmentsToRemove.Add(assignment); - this.logger.Debug("Header '{0}' for job ID {1} was released from peer ID {2}.", header, assignment.JobId, peerId); + this.logger.LogDebug("Header '{0}' for job ID {1} was released from peer ID {2}.", header, assignment.JobId, peerId); } foreach (AssignedDownload assignment in assignmentsToRemove) diff --git a/src/Stratis.Bitcoin/Builder/FullNodeFeatureExecutor.cs b/src/Stratis.Bitcoin/Builder/FullNodeFeatureExecutor.cs index 7ed8571007..84b6c49873 100644 --- a/src/Stratis.Bitcoin/Builder/FullNodeFeatureExecutor.cs +++ b/src/Stratis.Bitcoin/Builder/FullNodeFeatureExecutor.cs @@ -54,10 +54,10 @@ public void Initialize() { try { - this.logger.Info("Validating feature dependencies."); + this.logger.LogInformation("Validating feature dependencies."); this.Execute(feature => feature.ValidateDependencies(this.fullNode.Services)); - this.logger.Info("Initializing fullnode features."); + this.logger.LogInformation("Initializing fullnode features."); this.Execute(feature => { this.signals.Publish(new FullNodeEvent() { Message = $"Initializing feature '{feature.GetType().Name}'.", State = FullNodeState.Initializing.ToString() }); @@ -69,8 +69,8 @@ public void Initialize() } catch (Exception ex) { - this.logger.Error($"An error occurred starting the application: {ex}"); - this.logger.Trace("(-)[INITIALIZE_EXCEPTION]"); + this.logger.LogError($"An error occurred starting the application: {ex}"); + this.logger.LogTrace("(-)[INITIALIZE_EXCEPTION]"); throw; } } @@ -89,8 +89,8 @@ public void Dispose() } catch { - this.logger.Error("An error occurred stopping the application."); - this.logger.Trace("(-)[DISPOSE_EXCEPTION]"); + this.logger.LogError("An error occurred stopping the application."); + this.logger.LogTrace("(-)[DISPOSE_EXCEPTION]"); throw; } } @@ -105,7 +105,7 @@ private void Execute(Action callback, bool disposing = false) { if (this.fullNode.Services == null) { - this.logger.Trace("(-)[NO_SERVICES]"); + this.logger.LogTrace("(-)[NO_SERVICES]"); return; } @@ -154,7 +154,7 @@ private void Execute(Action callback, bool disposing = false) // Throw an aggregate exception if there were any exceptions. if (exceptions != null) { - this.logger.Trace("(-)[EXECUTION_FAILED]"); + this.logger.LogTrace("(-)[EXECUTION_FAILED]"); throw new AggregateException(exceptions); } } @@ -166,7 +166,7 @@ private void LogAndAddException(IFullNodeFeature feature, bool disposing, List string.Format(message, s)); - } - - public static void Info(this ILogger logger, string message, params object[] args) - { - logger.Log(LogLevel.Information, default, args, null, (s, e) => string.Format(message, s)); - } - - public static void Trace(this ILogger logger, string message, params object[] args) - { - logger.Log(LogLevel.Trace, default, args, null, (s, e) => string.Format(message, s)); - } - - public static void Warn(this ILogger logger, string message, params object[] args) - { - logger.Log(LogLevel.Warning, default, args, null, (s, e) => string.Format(message, s)); - } - - public static void Warn(this ILogger logger, Exception e, string message, params object[] args) - { - logger.Log(LogLevel.Warning, default, args, e, (s, e) => string.Format(message, s)); - } - - public static void Error(this ILogger logger, string message, params object[] args) - { - logger.Log(LogLevel.Error, default, args, null, (s, e) => string.Format(message, s)); - } - - public static void Error(this ILogger logger, Exception e, string message, params object[] args) - { - logger.Log(LogLevel.Error, default, args, e, (s, e) => string.Format(message, s)); - } - - public static void Fatal(this ILogger logger, string message, params object[] args) - { - logger.Log(LogLevel.Critical, default, args, null, (s, e) => string.Format(message, s)); - } - } -} diff --git a/src/Stratis.Bitcoin/Configuration/TextFileConfiguration.cs b/src/Stratis.Bitcoin/Configuration/TextFileConfiguration.cs index 411666cdbf..3087970c80 100644 --- a/src/Stratis.Bitcoin/Configuration/TextFileConfiguration.cs +++ b/src/Stratis.Bitcoin/Configuration/TextFileConfiguration.cs @@ -4,7 +4,6 @@ using System.Linq; using Microsoft.Extensions.Logging; using NBitcoin; -using Stratis.Bitcoin.Configuration.Logging; namespace Stratis.Bitcoin.Configuration { diff --git a/src/Stratis.Bitcoin/Consensus/FinalizedBlockInfoRepository.cs b/src/Stratis.Bitcoin/Consensus/FinalizedBlockInfoRepository.cs index caf14210d1..7ae67c8e01 100644 --- a/src/Stratis.Bitcoin/Consensus/FinalizedBlockInfoRepository.cs +++ b/src/Stratis.Bitcoin/Consensus/FinalizedBlockInfoRepository.cs @@ -99,10 +99,10 @@ public void Initialize(ChainedHeader chainTip) this.keyValueRepo.SaveValue(FinalizedBlockKey, resetFinalization); this.finalizedBlockInfo = resetFinalization; - this.logger.Info("Finalized block info reset."); + this.logger.LogInformation("Finalized block info reset."); } - this.logger.Info("Finalized block info initialized at '{0}'.", this.finalizedBlockInfo); + this.logger.LogInformation("Finalized block info initialized at '{0}'.", this.finalizedBlockInfo); this.finalizedBlockInfoPersistingTask = this.PersistFinalizedBlockInfoContinuouslyAsync(); this.asyncProvider.RegisterTask($"{nameof(FinalizedBlockInfoRepository)}.{nameof(this.finalizedBlockInfoPersistingTask)}", this.finalizedBlockInfoPersistingTask); @@ -138,7 +138,7 @@ private async Task PersistFinalizedBlockInfoContinuouslyAsync() this.keyValueRepo.SaveValue(FinalizedBlockKey, lastFinalizedBlock); - this.logger.Debug("Finalized info saved: '{0}'.", lastFinalizedBlock); + this.logger.LogDebug("Finalized info saved: '{0}'.", lastFinalizedBlock); } } @@ -169,7 +169,7 @@ public bool SaveFinalizedBlockHashAndHeight(uint256 hash, int height) { if (this.finalizedBlockInfo != null && height <= this.finalizedBlockInfo.Height) { - this.logger.Trace("(-)[CANT_GO_BACK]:false"); + this.logger.LogTrace("(-)[CANT_GO_BACK]:false"); return false; } diff --git a/src/Stratis.Bitcoin/Controllers/RestApiClientBase.cs b/src/Stratis.Bitcoin/Controllers/RestApiClientBase.cs index 4c12f1977d..6e8bff62cb 100644 --- a/src/Stratis.Bitcoin/Controllers/RestApiClientBase.cs +++ b/src/Stratis.Bitcoin/Controllers/RestApiClientBase.cs @@ -82,28 +82,28 @@ protected async Task SendPostRequestAsync(Model requ // Retry the following call according to the policy. await this.policy.ExecuteAsync(async token => { - this.logger.Debug("Sending request of type '{0}' to Uri '{1}'.", + this.logger.LogDebug("Sending request of type '{0}' to Uri '{1}'.", requestModel.GetType().FullName, publicationUri); response = await client.PostAsync(publicationUri, request, cancellation).ConfigureAwait(false); - this.logger.Debug("Response received: {0}", response); + this.logger.LogDebug("Response received: {0}", response); }, cancellation); } catch (OperationCanceledException) { - this.logger.Debug("Operation canceled."); - this.logger.Trace("(-)[CANCELLED]:null"); + this.logger.LogDebug("Operation canceled."); + this.logger.LogTrace("(-)[CANCELLED]:null"); return null; } catch (HttpRequestException ex) { - this.logger.Error("Target node is not ready to receive API calls at this time on {0}. Reason: {1}.", this.EndpointUrl, ex.Message); - this.logger.Debug("Failed to send a message. Exception: '{0}'.", ex); + this.logger.LogError("Target node is not ready to receive API calls at this time on {0}. Reason: {1}.", this.EndpointUrl, ex.Message); + this.logger.LogDebug("Failed to send a message. Exception: '{0}'.", ex); return new HttpResponseMessage() { ReasonPhrase = ex.Message, StatusCode = HttpStatusCode.InternalServerError }; } } - this.logger.Trace("(-)[SUCCESS]"); + this.logger.LogTrace("(-)[SUCCESS]"); return response; } @@ -132,19 +132,19 @@ private async Task ParseHttpResponseMessageAsync(HttpRespons { if (httpResponse == null) { - this.logger.Trace("(-)[NO_RESPONSE]:null"); + this.logger.LogTrace("(-)[NO_RESPONSE]:null"); return null; } if (!httpResponse.IsSuccessStatusCode) { - this.logger.Trace("(-)[NOT_SUCCESS_CODE]:null"); + this.logger.LogTrace("(-)[NOT_SUCCESS_CODE]:null"); return null; } if (httpResponse.Content == null) { - this.logger.Trace("(-)[NO_CONTENT]:null"); + this.logger.LogTrace("(-)[NO_CONTENT]:null"); return null; } @@ -153,13 +153,13 @@ private async Task ParseHttpResponseMessageAsync(HttpRespons if (successJson == null) { - this.logger.Trace("(-)[JSON_PARSING_FAILURE]:null"); + this.logger.LogTrace("(-)[JSON_PARSING_FAILURE]:null"); return null; } Response responseModel = JsonConvert.DeserializeObject(successJson); - this.logger.Trace("(-)[SUCCESS]"); + this.logger.LogTrace("(-)[SUCCESS]"); return responseModel; } @@ -183,35 +183,35 @@ protected async Task SendGetRequestAsync(string apiMethodNa // Retry the following call according to the policy. await this.policy.ExecuteAsync(async token => { - this.logger.Debug("Sending request to Url '{1}'.", url); + this.logger.LogDebug("Sending request to Url '{1}'.", url); response = await client.GetAsync(url, cancellation).ConfigureAwait(false); if (response != null) - this.logger.Debug("Response received: {0}", response); + this.logger.LogDebug("Response received: {0}", response); }, cancellation); } catch (OperationCanceledException) { - this.logger.Debug("Operation canceled."); - this.logger.Trace("(-)[CANCELLED]:null"); + this.logger.LogDebug("Operation canceled."); + this.logger.LogTrace("(-)[CANCELLED]:null"); return null; } catch (HttpRequestException ex) { - this.logger.Error("Target node is not ready to receive API calls at this time ({0})", this.EndpointUrl); - this.logger.Debug("Failed to send a message to '{0}'. Exception: '{1}'.", url, ex); + this.logger.LogError("Target node is not ready to receive API calls at this time ({0})", this.EndpointUrl); + this.logger.LogDebug("Failed to send a message to '{0}'. Exception: '{1}'.", url, ex); return new HttpResponseMessage() { ReasonPhrase = ex.Message, StatusCode = HttpStatusCode.InternalServerError }; } } - this.logger.Trace("(-)[SUCCESS]"); + this.logger.LogTrace("(-)[SUCCESS]"); return response; } protected virtual void OnRetry(Exception exception, TimeSpan delay) { - this.logger.Debug("Exception while calling API method: {0}. Retrying...", exception.ToString()); + this.logger.LogDebug("Exception while calling API method: {0}. Retrying...", exception.ToString()); } } diff --git a/src/Stratis.Bitcoin/OpReturnDataReader.cs b/src/Stratis.Bitcoin/OpReturnDataReader.cs index 8e2ea8901f..92b851ca1a 100644 --- a/src/Stratis.Bitcoin/OpReturnDataReader.cs +++ b/src/Stratis.Bitcoin/OpReturnDataReader.cs @@ -109,7 +109,7 @@ private string TryConvertValidOpReturnDataToAddress(byte[] data) } catch (Exception ex) { - this.logger.Debug("Address {destination} could not be converted to a valid address. Reason {message}.", destination, ex.Message); + this.logger.LogDebug("Address {destination} could not be converted to a valid address. Reason {message}.", destination, ex.Message); return null; } } @@ -124,7 +124,7 @@ private string TryConvertValidOpReturnDataToHash(byte[] data) } catch (Exception ex) { - this.logger.Debug("Candidate hash {data} could not be converted to a valid uint256. Reason {message}.", data, ex.Message); + this.logger.LogDebug("Candidate hash {data} could not be converted to a valid uint256. Reason {message}.", data, ex.Message); return null; } } diff --git a/src/Stratis.Bitcoin/Utilities/NodeStats.cs b/src/Stratis.Bitcoin/Utilities/NodeStats.cs index df5f998eec..646502d732 100644 --- a/src/Stratis.Bitcoin/Utilities/NodeStats.cs +++ b/src/Stratis.Bitcoin/Utilities/NodeStats.cs @@ -125,11 +125,11 @@ public string GetStats() } catch (OperationCanceledException) { - this.logger.Warn("{0} failed to provide inline statistics after {1} seconds, please investigate...", inlineStatItem.ComponentName, ComponentStatsWaitSeconds); + this.logger.LogWarning("{0} failed to provide inline statistics after {1} seconds, please investigate...", inlineStatItem.ComponentName, ComponentStatsWaitSeconds); } catch (Exception ex) { - this.logger.Warn("{0} failed to provide inline statistics: {1}", inlineStatItem.ComponentName, ex.ToString()); + this.logger.LogWarning("{0} failed to provide inline statistics: {1}", inlineStatItem.ComponentName, ex.ToString()); } }); @@ -154,11 +154,11 @@ public string GetStats() } catch (OperationCanceledException) { - this.logger.Warn("{0} failed to provide statistics after {1} seconds, please investigate...", componentStatItem.ComponentName, ComponentStatsWaitSeconds); + this.logger.LogWarning("{0} failed to provide statistics after {1} seconds, please investigate...", componentStatItem.ComponentName, ComponentStatsWaitSeconds); } catch (Exception ex) { - this.logger.Warn("{0} failed to provide statistics: {1}", componentStatItem.ComponentName, ex.ToString()); + this.logger.LogWarning("{0} failed to provide statistics: {1}", componentStatItem.ComponentName, ex.ToString()); } }); diff --git a/src/Stratis.Features.Collateral/CollateralChecker.cs b/src/Stratis.Features.Collateral/CollateralChecker.cs index be8f4b282d..189daabb64 100644 --- a/src/Stratis.Features.Collateral/CollateralChecker.cs +++ b/src/Stratis.Features.Collateral/CollateralChecker.cs @@ -94,7 +94,7 @@ public async Task InitializeAsync() foreach (CollateralFederationMember federationMember in this.federationManager.GetFederationMembers() .Cast().Where(x => x.CollateralAmount != null && x.CollateralAmount > 0)) { - this.logger.Info("Initializing federation member {0} with amount {1}.", federationMember.CollateralMainchainAddress, federationMember.CollateralAmount); + this.logger.LogInformation("Initializing federation member {0} with amount {1}.", federationMember.CollateralMainchainAddress, federationMember.CollateralAmount); this.balancesDataByAddress.Add(federationMember.CollateralMainchainAddress, null); } @@ -105,7 +105,7 @@ public async Task InitializeAsync() if (this.collateralUpdated) break; - this.logger.Warn("Node initialization will not continue until the gateway node responds."); + this.logger.LogWarning("Node initialization will not continue until the gateway node responds."); await this.DelayCollateralCheckAsync().ConfigureAwait(false); } @@ -148,7 +148,7 @@ private async Task DelayCollateralCheckAsync() } catch (OperationCanceledException) { - this.logger.Trace("(-)[CANCELLED]"); + this.logger.LogTrace("(-)[CANCELLED]"); } } @@ -163,33 +163,33 @@ private async Task UpdateCollateralInfoAsync(CancellationToken cancellation) if (addressesToCheck.Count == 0) { - this.logger.Info("None of the federation members has a collateral requirement configured."); + this.logger.LogInformation("None of the federation members has a collateral requirement configured."); } - this.logger.Debug("Addresses to check {0}.", addressesToCheck.Count); + this.logger.LogDebug("Addresses to check {0}.", addressesToCheck.Count); VerboseAddressBalancesResult verboseAddressBalanceResult = await this.blockStoreClient.GetVerboseAddressesBalancesDataAsync(addressesToCheck, cancellation).ConfigureAwait(false); if (verboseAddressBalanceResult == null) { - this.logger.Warn("Failed to update collateral, please ensure that the mainnet gateway node is running and it's API feature is enabled."); - this.logger.Trace("(-)[CALL_RETURNED_NULL_RESULT]:false"); + this.logger.LogWarning("Failed to update collateral, please ensure that the mainnet gateway node is running and it's API feature is enabled."); + this.logger.LogTrace("(-)[CALL_RETURNED_NULL_RESULT]:false"); return; } if (!string.IsNullOrEmpty(verboseAddressBalanceResult.Reason)) { - this.logger.Warn("Failed to fetch address balances from the counter chain node : {0}", verboseAddressBalanceResult.Reason); - this.logger.Trace("(-)[FAILED]:{0}", verboseAddressBalanceResult.Reason); + this.logger.LogWarning("Failed to fetch address balances from the counter chain node : {0}", verboseAddressBalanceResult.Reason); + this.logger.LogTrace("(-)[FAILED]:{0}", verboseAddressBalanceResult.Reason); return; } - this.logger.Debug("Addresses received {0}.", verboseAddressBalanceResult.BalancesData.Count); + this.logger.LogDebug("Addresses received {0}.", verboseAddressBalanceResult.BalancesData.Count); if (verboseAddressBalanceResult.BalancesData.Count != addressesToCheck.Count) { - this.logger.Debug("Expected {0} data entries but received {1}.", addressesToCheck.Count, verboseAddressBalanceResult.BalancesData.Count); - this.logger.Trace("(-)[CALL_RETURNED_INCONSISTENT_DATA]:false"); + this.logger.LogDebug("Expected {0} data entries but received {1}.", addressesToCheck.Count, verboseAddressBalanceResult.BalancesData.Count); + this.logger.LogTrace("(-)[CALL_RETURNED_INCONSISTENT_DATA]:false"); return; } @@ -197,7 +197,7 @@ private async Task UpdateCollateralInfoAsync(CancellationToken cancellation) { foreach (AddressIndexerData balanceData in verboseAddressBalanceResult.BalancesData) { - this.logger.Debug("Updating federation member address {0}.", balanceData.Address); + this.logger.LogDebug("Updating federation member address {0}.", balanceData.Address); this.balancesDataByAddress[balanceData.Address] = balanceData; } @@ -212,7 +212,7 @@ public bool CheckCollateral(IFederationMember federationMember, int heightToChec { if (!this.collateralUpdated) { - this.logger.Debug("(-)[NOT_INITIALIZED]"); + this.logger.LogDebug("(-)[NOT_INITIALIZED]"); throw new Exception("Component is not initialized!"); } @@ -220,7 +220,7 @@ public bool CheckCollateral(IFederationMember federationMember, int heightToChec if (member == null) { - this.logger.Debug("(-)[WRONG_TYPE]"); + this.logger.LogDebug("(-)[WRONG_TYPE]"); throw new ArgumentException($"{nameof(federationMember)} should be of type: {nameof(CollateralFederationMember)}."); } @@ -228,14 +228,14 @@ public bool CheckCollateral(IFederationMember federationMember, int heightToChec { if (heightToCheckAt > this.counterChainConsensusTipHeight - this.maxReorgLength) { - this.logger.Debug("(-)[HEIGHTTOCHECK_HIGHER_THAN_COUNTER_TIP_LESS_MAXREORG]:{0}={1}, {2}={3}:false", nameof(heightToCheckAt), heightToCheckAt, nameof(this.counterChainConsensusTipHeight), this.counterChainConsensusTipHeight); + this.logger.LogDebug("(-)[HEIGHTTOCHECK_HIGHER_THAN_COUNTER_TIP_LESS_MAXREORG]:{0}={1}, {2}={3}:false", nameof(heightToCheckAt), heightToCheckAt, nameof(this.counterChainConsensusTipHeight), this.counterChainConsensusTipHeight); return false; } } if ((member.CollateralAmount == null) || (member.CollateralAmount == 0)) { - this.logger.Debug("(-)[NO_COLLATERAL_REQUIREMENT]:true"); + this.logger.LogDebug("(-)[NO_COLLATERAL_REQUIREMENT]:true"); return true; } @@ -246,13 +246,13 @@ public bool CheckCollateral(IFederationMember federationMember, int heightToChec if (balanceData == null) { // No data. Assume collateral is 0. It's ok if there is no collateral set for that fed member. - this.logger.Debug("(-)[NO_DATA]:{0}={1}", nameof(this.balancesDataByAddress.Count), this.balancesDataByAddress.Count); + this.logger.LogDebug("(-)[NO_DATA]:{0}={1}", nameof(this.balancesDataByAddress.Count), this.balancesDataByAddress.Count); return 0 >= member.CollateralAmount; } long balance = balanceData.BalanceChanges.Where(x => x.BalanceChangedHeight <= heightToCheckAt).CalculateBalance(); - this.logger.Info("Calculated balance for '{0}' at {1} is {2}, collateral requirement is {3}.", member.CollateralMainchainAddress, heightToCheckAt, Money.Satoshis(balance).ToUnit(MoneyUnit.BTC), member.CollateralAmount); + this.logger.LogInformation("Calculated balance for '{0}' at {1} is {2}, collateral requirement is {3}.", member.CollateralMainchainAddress, heightToCheckAt, Money.Satoshis(balance).ToUnit(MoneyUnit.BTC), member.CollateralAmount); return balance >= member.CollateralAmount.Satoshi; } @@ -264,15 +264,15 @@ private void OnFedMemberKicked(FedMemberKicked fedMemberKicked) { if (fedMemberKicked.KickedMember is CollateralFederationMember collateralFederationMember) { - this.logger.Debug("Removing federation member '{0}' with collateral address '{1}'.", collateralFederationMember.PubKey, collateralFederationMember.CollateralMainchainAddress); + this.logger.LogDebug("Removing federation member '{0}' with collateral address '{1}'.", collateralFederationMember.PubKey, collateralFederationMember.CollateralMainchainAddress); if (!string.IsNullOrEmpty(collateralFederationMember.CollateralMainchainAddress)) this.balancesDataByAddress.Remove(collateralFederationMember.CollateralMainchainAddress); else - this.logger.Debug("(-)[NO_COLLATERAL_ADDRESS]:{0}='{1}'", nameof(fedMemberKicked.KickedMember.PubKey), fedMemberKicked.KickedMember.PubKey); + this.logger.LogDebug("(-)[NO_COLLATERAL_ADDRESS]:{0}='{1}'", nameof(fedMemberKicked.KickedMember.PubKey), fedMemberKicked.KickedMember.PubKey); } else { - this.logger.Error("(-)[NOT_A_COLLATERAL_MEMBER]:{0}='{1}'", nameof(fedMemberKicked.KickedMember.PubKey), fedMemberKicked.KickedMember.PubKey); + this.logger.LogError("(-)[NOT_A_COLLATERAL_MEMBER]:{0}='{1}'", nameof(fedMemberKicked.KickedMember.PubKey), fedMemberKicked.KickedMember.PubKey); } } } @@ -285,19 +285,19 @@ private void OnFedMemberAdded(FedMemberAdded fedMemberAdded) { if (string.IsNullOrEmpty(collateralFederationMember.CollateralMainchainAddress)) { - this.logger.Debug("(-)[NO_COLLATERAL_ADDRESS]:{0}='{1}'", nameof(fedMemberAdded.AddedMember.PubKey), fedMemberAdded.AddedMember.PubKey); + this.logger.LogDebug("(-)[NO_COLLATERAL_ADDRESS]:{0}='{1}'", nameof(fedMemberAdded.AddedMember.PubKey), fedMemberAdded.AddedMember.PubKey); return; } if (!this.balancesDataByAddress.ContainsKey(collateralFederationMember.CollateralMainchainAddress)) { - this.logger.Debug("Adding federation member '{0}' with collateral address '{1}'.", collateralFederationMember.PubKey, collateralFederationMember.CollateralMainchainAddress); + this.logger.LogDebug("Adding federation member '{0}' with collateral address '{1}'.", collateralFederationMember.PubKey, collateralFederationMember.CollateralMainchainAddress); this.balancesDataByAddress.Add(collateralFederationMember.CollateralMainchainAddress, null); } } else { - this.logger.Error("(-)[NOT_A_COLLATERAL_MEMBER]:{0}='{1}'", nameof(fedMemberAdded.AddedMember.PubKey), fedMemberAdded.AddedMember.PubKey); + this.logger.LogError("(-)[NOT_A_COLLATERAL_MEMBER]:{0}='{1}'", nameof(fedMemberAdded.AddedMember.PubKey), fedMemberAdded.AddedMember.PubKey); } } } diff --git a/src/Stratis.Features.Collateral/CollateralController.cs b/src/Stratis.Features.Collateral/CollateralController.cs index 3b336b703b..4e258d889b 100644 --- a/src/Stratis.Features.Collateral/CollateralController.cs +++ b/src/Stratis.Features.Collateral/CollateralController.cs @@ -57,7 +57,7 @@ public async Task JoinFederationAsync([FromBody] JoinFederationRe // Checks that the request is valid. if (!this.ModelState.IsValid) { - this.logger.Trace("(-)[MODEL_STATE_INVALID]"); + this.logger.LogTrace("(-)[MODEL_STATE_INVALID]"); return ModelStateErrors.BuildErrorResponse(this.ModelState); } @@ -73,13 +73,13 @@ public async Task JoinFederationAsync([FromBody] JoinFederationRe MinerPublicKey = minerPubKey.ToHex() }; - this.logger.Trace("(-):'{0}'", model); + this.logger.LogTrace("(-):'{0}'", model); return this.Json(model); } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); - this.logger.Trace("(-)[ERROR]"); + this.logger.LogError("Exception occurred: {0}", e.ToString()); + this.logger.LogTrace("(-)[ERROR]"); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } diff --git a/src/Stratis.Features.Collateral/JoinFederationRequestMonitor.cs b/src/Stratis.Features.Collateral/JoinFederationRequestMonitor.cs index a6169a143a..3685e01171 100644 --- a/src/Stratis.Features.Collateral/JoinFederationRequestMonitor.cs +++ b/src/Stratis.Features.Collateral/JoinFederationRequestMonitor.cs @@ -89,7 +89,7 @@ public void OnBlockConnected(BlockConnected blockConnectedData) if (collateralAmount != expectedCollateralAmount) { - this.logger.Debug("Ignoring voting collateral amount '{0}', when expecting '{1}'.", collateralAmount, expectedCollateralAmount); + this.logger.LogDebug("Ignoring voting collateral amount '{0}', when expecting '{1}'.", collateralAmount, expectedCollateralAmount); continue; } @@ -104,7 +104,7 @@ public void OnBlockConnected(BlockConnected blockConnectedData) // Nothing to do if already voted. if (this.votingManager.AlreadyVotingFor(VoteKey.AddFederationMember, federationMemberBytes)) { - this.logger.Debug("Skipping because already voted for adding '{0}'.", request.PubKey.ToHex()); + this.logger.LogDebug("Skipping because already voted for adding '{0}'.", request.PubKey.ToHex()); continue; } @@ -119,12 +119,12 @@ public void OnBlockConnected(BlockConnected blockConnectedData) PubKey key = PubKey.RecoverFromMessage(request.SignatureMessage, request.Signature); if (key.Hash != request.CollateralMainchainAddress) { - this.logger.Debug("Invalid collateral address validation signature for joining federation via transaction '{0}'", tx.GetHash()); + this.logger.LogDebug("Invalid collateral address validation signature for joining federation via transaction '{0}'", tx.GetHash()); continue; } // Vote to add the member. - this.logger.Debug("Voting to add federation member '{0}'.", request.PubKey.ToHex()); + this.logger.LogDebug("Voting to add federation member '{0}'.", request.PubKey.ToHex()); this.votingManager.ScheduleVote(new VotingData() { @@ -135,7 +135,7 @@ public void OnBlockConnected(BlockConnected blockConnectedData) } catch (Exception err) { - this.logger.Error(err.Message); + this.logger.LogError(err.Message); } } } diff --git a/src/Stratis.Features.FederatedPeg/Controllers/CollateralVotingController.cs b/src/Stratis.Features.FederatedPeg/Controllers/CollateralVotingController.cs index fc1950ed64..a2a22ac252 100644 --- a/src/Stratis.Features.FederatedPeg/Controllers/CollateralVotingController.cs +++ b/src/Stratis.Features.FederatedPeg/Controllers/CollateralVotingController.cs @@ -78,7 +78,7 @@ private IActionResult VoteAddKickFedMember(CollateralFederationMemberModel reque } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "There was a problem executing a command.", e.ToString()); } } diff --git a/src/Stratis.Features.FederatedPeg/Controllers/FederationGatewayController.cs b/src/Stratis.Features.FederatedPeg/Controllers/FederationGatewayController.cs index cbeaa03d80..18829d8565 100644 --- a/src/Stratis.Features.FederatedPeg/Controllers/FederationGatewayController.cs +++ b/src/Stratis.Features.FederatedPeg/Controllers/FederationGatewayController.cs @@ -113,7 +113,7 @@ public async Task GetMaturedBlockDepositsAsync([FromQuery(Name = } catch (Exception e) { - this.logger.Error("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.GetMaturedBlockDeposits, e.Message); + this.logger.LogError("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.GetMaturedBlockDeposits, e.Message); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, $"Could not re-sync matured block deposits: {e.Message}", e.ToString()); } } @@ -243,7 +243,7 @@ public IActionResult GetFederationMemberInfo() } catch (Exception e) { - this.logger.Error("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.GetFederationMemberInfo, e.Message); + this.logger.LogError("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.GetFederationMemberInfo, e.Message); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -286,7 +286,7 @@ public IActionResult GetInfo() } catch (Exception e) { - this.logger.Error("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.GetFederationInfo, e.Message); + this.logger.LogError("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.GetFederationInfo, e.Message); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -319,7 +319,7 @@ public IActionResult AddFederationMemberIp([FromBody] FederationMemberIpModel mo } catch (Exception e) { - this.logger.Error("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.FederationMemberIpAdd, e.Message); + this.logger.LogError("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.FederationMemberIpAdd, e.Message); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -352,7 +352,7 @@ public IActionResult RemoveFederationMemberIp([FromBody] FederationMemberIpModel } catch (Exception e) { - this.logger.Error("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.FederationMemberIpRemove, e.Message); + this.logger.LogError("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.FederationMemberIpRemove, e.Message); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -392,7 +392,7 @@ public IActionResult ReplaceFederationMemberIp([FromBody] ReplaceFederationMembe } catch (Exception e) { - this.logger.Error("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.FederationMemberIpReplace, e.Message); + this.logger.LogError("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.FederationMemberIpReplace, e.Message); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } diff --git a/src/Stratis.Features.FederatedPeg/Controllers/FederationWalletController.cs b/src/Stratis.Features.FederatedPeg/Controllers/FederationWalletController.cs index bb5a83e2d0..56cf390d87 100644 --- a/src/Stratis.Features.FederatedPeg/Controllers/FederationWalletController.cs +++ b/src/Stratis.Features.FederatedPeg/Controllers/FederationWalletController.cs @@ -101,7 +101,7 @@ public IActionResult GetGeneralInfo() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -144,7 +144,7 @@ public IActionResult GetBalance() } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -176,7 +176,7 @@ public IActionResult GetHistory([FromQuery] int maxEntriesToReturn) } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -253,7 +253,7 @@ public IActionResult EnableFederation([FromBody] EnableFederationRequest request } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } @@ -314,7 +314,7 @@ public IActionResult RemoveTransactions([FromQuery] RemoveFederationTransactions } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } diff --git a/src/Stratis.Features.FederatedPeg/Controllers/MultisigController.cs b/src/Stratis.Features.FederatedPeg/Controllers/MultisigController.cs index cd48f4ecaa..c8dbf57b34 100644 --- a/src/Stratis.Features.FederatedPeg/Controllers/MultisigController.cs +++ b/src/Stratis.Features.FederatedPeg/Controllers/MultisigController.cs @@ -86,7 +86,7 @@ public IActionResult BuildTransaction([FromBody] BuildMultisigTransactionRequest } catch (Exception e) { - this.logger.Error("Exception occurred: {0}", e.ToString()); + this.logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } diff --git a/src/Stratis.Features.FederatedPeg/Coordination/ConversionRequestCoordinationService.cs b/src/Stratis.Features.FederatedPeg/Coordination/ConversionRequestCoordinationService.cs index 2746c092f9..71ddca6296 100644 --- a/src/Stratis.Features.FederatedPeg/Coordination/ConversionRequestCoordinationService.cs +++ b/src/Stratis.Features.FederatedPeg/Coordination/ConversionRequestCoordinationService.cs @@ -86,7 +86,7 @@ public void AddVote(string requestId, BigInteger transactionId, PubKey pubKey) // Check if the pubkey node has voted for this request. if (!voted.Contains(pubKey)) { - this.logger.Debug("Adding vote for request '{0}' (transactionId '{1}') from pubkey {2}.", requestId, transactionId, pubKey.ToHex()); + this.logger.LogDebug("Adding vote for request '{0}' (transactionId '{1}') from pubkey {2}.", requestId, transactionId, pubKey.ToHex()); voted.Add(pubKey); diff --git a/src/Stratis.Features.FederatedPeg/Coordination/ConversionRequestFeeService.cs b/src/Stratis.Features.FederatedPeg/Coordination/ConversionRequestFeeService.cs index 8a35963512..4306c4dd63 100644 --- a/src/Stratis.Features.FederatedPeg/Coordination/ConversionRequestFeeService.cs +++ b/src/Stratis.Features.FederatedPeg/Coordination/ConversionRequestFeeService.cs @@ -127,7 +127,7 @@ public async Task AgreeFeeForConversionRequestAsync { if (conversionRequestSyncStart.AddMinutes(2) <= this.dateTimeProvider.GetUtcNow()) { - this.logger.Warn($"A fee for conversion request '{requestId}' failed to reach consensus after 2 minutes, ignoring."); + this.logger.LogWarning($"A fee for conversion request '{requestId}' failed to reach consensus after 2 minutes, ignoring."); interopConversionRequestFee.State = InteropFeeState.FailRevertToFallback; this.interopRequestKeyValueStore.SaveValueJson(requestId, interopConversionRequestFee); break; @@ -183,7 +183,7 @@ private InteropConversionRequestFee CreateInteropConversionRequestFeeLocked(stri { interopConversionRequest = new InteropConversionRequestFee() { RequestId = requestId, BlockHeight = blockHeight, State = InteropFeeState.ProposalInProgress }; this.interopRequestKeyValueStore.SaveValueJson(requestId, interopConversionRequest); - this.logger.Debug($"InteropConversionRequestFee object for request '{requestId}' has been created."); + this.logger.LogDebug($"InteropConversionRequestFee object for request '{requestId}' has been created."); } return interopConversionRequest; @@ -205,10 +205,10 @@ private async Task SubmitProposalForInteropFeeForConversionRequestLockedAsync(In interopConversionRequestFee.FeeProposals.Add(new InterOpFeeToMultisig() { BlockHeight = interopConversionRequestFee.BlockHeight, PubKey = this.federationManager.CurrentFederationKey.PubKey.ToHex(), FeeAmount = candidateFee }); this.interopRequestKeyValueStore.SaveValueJson(interopConversionRequestFee.RequestId, interopConversionRequestFee, true); - this.logger.Debug($"Adding this node's proposal fee of {candidateFee} for conversion request id '{interopConversionRequestFee.RequestId}'."); + this.logger.LogDebug($"Adding this node's proposal fee of {candidateFee} for conversion request id '{interopConversionRequestFee.RequestId}'."); } - this.logger.Debug($"{interopConversionRequestFee.FeeProposals.Count} node(s) has proposed a fee for conversion request id '{interopConversionRequestFee.RequestId}'."); + this.logger.LogDebug($"{interopConversionRequestFee.FeeProposals.Count} node(s) has proposed a fee for conversion request id '{interopConversionRequestFee.RequestId}'."); if (HasFeeProposalBeenConcluded(interopConversionRequestFee)) { @@ -219,7 +219,7 @@ private async Task SubmitProposalForInteropFeeForConversionRequestLockedAsync(In this.interopRequestKeyValueStore.SaveValueJson(interopConversionRequestFee.RequestId, interopConversionRequestFee, true); IEnumerable values = interopConversionRequestFee.FeeProposals.Select(s => Convert.ToInt64(s.FeeAmount)); - this.logger.Debug($"Proposal fee for request id '{interopConversionRequestFee.RequestId}' has concluded, average amount: {values.Average()}"); + this.logger.LogDebug($"Proposal fee for request id '{interopConversionRequestFee.RequestId}' has concluded, average amount: {values.Average()}"); } } @@ -238,7 +238,7 @@ private async Task AgreeOnInteropFeeForConversionRequestLockedAsync(InteropConve { if (!HasFeeProposalBeenConcluded(interopConversionRequestFee)) { - this.logger.Error($"Cannot vote on fee proposal for request id '{interopConversionRequestFee.RequestId}' as it hasn't concluded yet."); + this.logger.LogError($"Cannot vote on fee proposal for request id '{interopConversionRequestFee.RequestId}' as it hasn't concluded yet."); return; } @@ -251,10 +251,10 @@ private async Task AgreeOnInteropFeeForConversionRequestLockedAsync(InteropConve interopConversionRequestFee.FeeVotes.Add(interOpFeeToMultisig); this.interopRequestKeyValueStore.SaveValueJson(interopConversionRequestFee.RequestId, interopConversionRequestFee, true); - this.logger.Debug($"Creating fee vote for conversion request id '{interopConversionRequestFee.RequestId}' with a fee amount of {new Money(candidateFee)}."); + this.logger.LogDebug($"Creating fee vote for conversion request id '{interopConversionRequestFee.RequestId}' with a fee amount of {new Money(candidateFee)}."); } - this.logger.Debug($"{interopConversionRequestFee.FeeVotes.Count} node(s) has voted on a fee for conversion request id '{interopConversionRequestFee.RequestId}'."); + this.logger.LogDebug($"{interopConversionRequestFee.FeeVotes.Count} node(s) has voted on a fee for conversion request id '{interopConversionRequestFee.RequestId}'."); if (HasFeeVoteBeenConcluded(interopConversionRequestFee)) ConcludeInteropConversionRequestFee(interopConversionRequestFee); @@ -286,7 +286,7 @@ public async Task MultiSigMemberProposedInteropFeeAsync(stri interopConversionRequestFee.FeeProposals.Add(new InterOpFeeToMultisig() { BlockHeight = interopConversionRequestFee.BlockHeight, PubKey = pubKey.ToHex(), FeeAmount = feeAmount }); this.interopRequestKeyValueStore.SaveValueJson(interopConversionRequestFee.RequestId, interopConversionRequestFee, true); - this.logger.Debug($"Received conversion request proposal '{requestId}' from '{pubKey}', proposing fee of {new Money(feeAmount)}."); + this.logger.LogDebug($"Received conversion request proposal '{requestId}' from '{pubKey}', proposing fee of {new Money(feeAmount)}."); } // This node would have proposed this fee if the InteropConversionRequestFee object exists. @@ -312,7 +312,7 @@ public async Task MultiSigMemberAgreedOnInteropFeeAsync(string interopConversionRequestFee.FeeVotes.Add(new InterOpFeeToMultisig() { BlockHeight = interopConversionRequestFee.BlockHeight, PubKey = pubKey.ToHex(), FeeAmount = feeAmount }); this.interopRequestKeyValueStore.SaveValueJson(interopConversionRequestFee.RequestId, interopConversionRequestFee, true); - this.logger.Debug($"Received conversion request fee vote '{requestId}' from '{pubKey} for a fee of {new Money(feeAmount)}."); + this.logger.LogDebug($"Received conversion request fee vote '{requestId}' from '{pubKey} for a fee of {new Money(feeAmount)}."); } // This node would have voted on this if the InteropConversionRequestFee object exists. @@ -339,7 +339,7 @@ private bool IsFeeWithinAcceptableRange(List proposals, st if (feeAmount < (currentAverage - (currentAverage * FeeProposalRange)) || feeAmount > (currentAverage + (currentAverage * FeeProposalRange))) { - this.logger.Debug($"Conversion request '{requestId}' received from pubkey '{pubKey}' with amount {feeAmount} is out of range of the current average of {currentAverage}, skipping."); + this.logger.LogDebug($"Conversion request '{requestId}' received from pubkey '{pubKey}' with amount {feeAmount} is out of range of the current average of {currentAverage}, skipping."); return false; } @@ -353,7 +353,7 @@ private bool EstimateConversionTransactionFee(out ulong candidateFee) var conversionTransactionFee = this.externalApiPoller.EstimateConversionTransactionFee(); if (conversionTransactionFee == -1) { - this.logger.Debug("External poller returned -1, will retry."); + this.logger.LogDebug("External poller returned -1, will retry."); return false; } @@ -379,7 +379,7 @@ private void ConcludeInteropConversionRequestFee(InteropConversionRequestFee int foreach (InterOpFeeToMultisig vote in interopConversionRequestFee.FeeVotes) { - this.logger.Debug($"Pubkey '{vote.PubKey}' voted for {new Money(vote.FeeAmount)}."); + this.logger.LogDebug($"Pubkey '{vote.PubKey}' voted for {new Money(vote.FeeAmount)}."); } // Try and find the majority vote @@ -393,7 +393,7 @@ private void ConcludeInteropConversionRequestFee(InteropConversionRequestFee int interopConversionRequestFee.State = InteropFeeState.AgreeanceConcluded; this.interopRequestKeyValueStore.SaveValueJson(interopConversionRequestFee.RequestId, interopConversionRequestFee, true); - this.logger.Debug($"Voting on fee for request id '{interopConversionRequestFee.RequestId}' has concluded, amount: {new Money(interopConversionRequestFee.Amount)}"); + this.logger.LogDebug($"Voting on fee for request id '{interopConversionRequestFee.RequestId}' has concluded, amount: {new Money(interopConversionRequestFee.Amount)}"); } private void AddComponentStats(StringBuilder benchLog) diff --git a/src/Stratis.Features.FederatedPeg/Distribution/RewardClaimer.cs b/src/Stratis.Features.FederatedPeg/Distribution/RewardClaimer.cs index 733c7ccf98..124bdc8717 100644 --- a/src/Stratis.Features.FederatedPeg/Distribution/RewardClaimer.cs +++ b/src/Stratis.Features.FederatedPeg/Distribution/RewardClaimer.cs @@ -86,7 +86,7 @@ public Transaction BuildRewardTransaction(bool batchRewards) var startFromHeight = (this.lastDistributionHeight + 1) - minStakeConfirmations; - this.logger.Info($"[Reward Batching] Calculating rewards from height {startFromHeight} to {startFromHeight + this.network.RewardClaimerBlockInterval} (last distribution [{this.lastDistributionHeight + 1}] less minimum stake confirmations [{minStakeConfirmations}])."); + this.logger.LogInformation($"[Reward Batching] Calculating rewards from height {startFromHeight} to {startFromHeight + this.network.RewardClaimerBlockInterval} (last distribution [{this.lastDistributionHeight + 1}] less minimum stake confirmations [{minStakeConfirmations}])."); for (int height = startFromHeight; height < startFromHeight + this.network.RewardClaimerBlockInterval; height++) { // Get the block that is minStakeConfirmations behind the current tip. @@ -170,13 +170,13 @@ private Transaction BuildRewardTransaction(List coins) if (errors.Any()) { foreach (TransactionPolicyError error in errors) - this.logger.Warn("Unable to validate reward claim transaction '{0}', error: {1}", builtTransaction.ToHex(), error.ToString()); + this.logger.LogWarning("Unable to validate reward claim transaction '{0}', error: {1}", builtTransaction.ToHex(), error.ToString()); // Not much further can be done at this point. return null; } - this.logger.Info($"Reward distribution transaction '{builtTransaction.GetHash()}' built; sending {builtTransaction.TotalOut} to federation '{this.network.Federations.GetOnlyFederation().MultisigScript.PaymentScript}'."); + this.logger.LogInformation($"Reward distribution transaction '{builtTransaction.GetHash()}' built; sending {builtTransaction.TotalOut} to federation '{this.network.Federations.GetOnlyFederation().MultisigScript.PaymentScript}'."); return builtTransaction; } @@ -191,7 +191,7 @@ private Block GetMaturedBlock(int applicableHeight) // If we still don't have the block data, just return. if (maturedBlock == null) { - this.logger.Debug("Consensus does not have the block data for '{0}'", chainedHeader); + this.logger.LogDebug("Consensus does not have the block data for '{0}'", chainedHeader); return null; } @@ -215,7 +215,7 @@ private void OnBlockConnected(BlockConnected blockConnected) // This is could happen due to a reorg and therefore we do nothing. if (blockConnected.ConnectedBlock.ChainedHeader.Height <= (this.lastDistributionHeight + 1)) { - this.logger.Info($"Reward claiming skipped as block window already processed; Block connected at {blockConnected.ConnectedBlock.ChainedHeader.Height}; Last distribution at {this.lastDistributionHeight}."); + this.logger.LogInformation($"Reward claiming skipped as block window already processed; Block connected at {blockConnected.ConnectedBlock.ChainedHeader.Height}; Last distribution at {this.lastDistributionHeight}."); return; } @@ -229,19 +229,19 @@ private void OnBlockConnected(BlockConnected blockConnected) if (blockConnected.ConnectedBlock.ChainedHeader.Height - (this.lastDistributionHeight + 1) > this.network.RewardClaimerBlockInterval) { this.lastDistributionHeight = blockConnected.ConnectedBlock.ChainedHeader.Height - this.network.RewardClaimerBlockInterval - 1; - this.logger.Info($"[Reward Batching] The last reward window was skipped, resetting to {this.lastDistributionHeight}."); + this.logger.LogInformation($"[Reward Batching] The last reward window was skipped, resetting to {this.lastDistributionHeight}."); } - this.logger.Info($"[Reward Batching] Triggered at height {blockConnected.ConnectedBlock.ChainedHeader.Height}."); + this.logger.LogInformation($"[Reward Batching] Triggered at height {blockConnected.ConnectedBlock.ChainedHeader.Height}."); BuildAndCompleteRewardClaim(true, this.lastDistributionHeight + this.network.RewardClaimerBlockInterval); } else - this.logger.Info($"[Reward Batching] The next distribution will be triggered at block {this.lastDistributionHeight + 1 + this.network.RewardClaimerBlockInterval}."); + this.logger.LogInformation($"[Reward Batching] The next distribution will be triggered at block {this.lastDistributionHeight + 1 + this.network.RewardClaimerBlockInterval}."); } else { - this.logger.Info($"Per block reward claiming in effect until block {this.network.RewardClaimerBatchActivationHeight} (rewards are not batched)."); + this.logger.LogInformation($"Per block reward claiming in effect until block {this.network.RewardClaimerBatchActivationHeight} (rewards are not batched)."); BuildAndCompleteRewardClaim(false, blockConnected.ConnectedBlock.ChainedHeader.Height); } } @@ -275,13 +275,13 @@ private void LoadLastDistributionHeight() if (this.lastDistributionHeight == 0) this.lastDistributionHeight = this.network.RewardClaimerBatchActivationHeight; - this.logger.Info($"Last reward distribution height set to {this.lastDistributionHeight}."); + this.logger.LogInformation($"Last reward distribution height set to {this.lastDistributionHeight}."); } private void SaveLastDistributionHeight() { this.keyValueRepository.SaveValueJson(LastDistributionHeightKey, this.lastDistributionHeight); - this.logger.Info($"Last reward distribution saved as {this.lastDistributionHeight}."); + this.logger.LogInformation($"Last reward distribution saved as {this.lastDistributionHeight}."); } public void Dispose() diff --git a/src/Stratis.Features.FederatedPeg/Distribution/RewardDistributionManager.cs b/src/Stratis.Features.FederatedPeg/Distribution/RewardDistributionManager.cs index c579365d22..80240f7973 100644 --- a/src/Stratis.Features.FederatedPeg/Distribution/RewardDistributionManager.cs +++ b/src/Stratis.Features.FederatedPeg/Distribution/RewardDistributionManager.cs @@ -110,7 +110,7 @@ public List DistributeToMultisigNodes(int blockHeight, Money fee) multiSigMinerScripts.Add(minerScript); } - this.logger.Info("Fee reward to multisig node at main chain height {0} will distribute {1} STRAX between {2} multisig mining keys.", blockHeight, fee, multiSigMinerScripts.Count); + this.logger.LogInformation("Fee reward to multisig node at main chain height {0} will distribute {1} STRAX between {2} multisig mining keys.", blockHeight, fee, multiSigMinerScripts.Count); Money feeReward = fee / multiSigMinerScripts.Count; @@ -125,12 +125,12 @@ public List DistributeToMultisigNodes(int blockHeight, Money fee) multiSigRecipients.Add(new Recipient() { Amount = feeReward, ScriptPubKey = p2pkh }); - this.logger.Debug($"Paying multisig member '{pubKey}' {feeReward} STRAX."); + this.logger.LogDebug($"Paying multisig member '{pubKey}' {feeReward} STRAX."); } else { multiSigRecipients.Add(new Recipient() { Amount = feeReward, ScriptPubKey = multiSigMinerScript }); - this.logger.Debug($"Paying multisig member '{multiSigMinerScript.ToHex()}' (hex) {feeReward} STRAX."); + this.logger.LogDebug($"Paying multisig member '{multiSigMinerScript.ToHex()}' (hex) {feeReward} STRAX."); } } @@ -143,7 +143,7 @@ public List Distribute(int heightOfRecordedDistributionDeposit, Money { // First determine the main chain blockheight of the recorded deposit less max reorg * 2 (epoch window) var applicableMainChainDepositHeight = heightOfRecordedDistributionDeposit - this.epochWindow; - this.logger.Trace("{0} : {1}", nameof(applicableMainChainDepositHeight), applicableMainChainDepositHeight); + this.logger.LogTrace("{0} : {1}", nameof(applicableMainChainDepositHeight), applicableMainChainDepositHeight); // Then find the header on the sidechain that contains the applicable commitment height. int sidechainTipHeight = this.chainIndexer.Tip.Height; @@ -175,7 +175,7 @@ public List Distribute(int heightOfRecordedDistributionDeposit, Money if (commitmentHeightToCheck != null) { - this.logger.Trace("{0} : {1}={2}", currentHeader, nameof(commitmentHeightToCheck), commitmentHeightToCheck); + this.logger.LogTrace("{0} : {1}={2}", currentHeader, nameof(commitmentHeightToCheck), commitmentHeightToCheck); if (commitmentHeightToCheck <= applicableMainChainDepositHeight) break; @@ -188,7 +188,7 @@ public List Distribute(int heightOfRecordedDistributionDeposit, Money // Get the set of miners (more specifically, the scriptPubKeys they generated blocks with) to distribute rewards to. // Based on the computed 'common block height' we define the distribution epoch: int sidechainStartHeight = currentHeader.Height; - this.logger.Trace("Initial {0} : {1}", nameof(sidechainStartHeight), sidechainStartHeight); + this.logger.LogTrace("Initial {0} : {1}", nameof(sidechainStartHeight), sidechainStartHeight); // This is a special case which will not be the case on the live network. if (sidechainStartHeight < this.epoch) @@ -198,7 +198,7 @@ public List Distribute(int heightOfRecordedDistributionDeposit, Money if (sidechainStartHeight > this.epoch) sidechainStartHeight -= this.epoch; - this.logger.Trace("Adjusted {0} : {1}", nameof(sidechainStartHeight), sidechainStartHeight); + this.logger.LogTrace("Adjusted {0} : {1}", nameof(sidechainStartHeight), sidechainStartHeight); // Ensure that the dictionary is cleared on every run. // As this is a static class, new instances of this dictionary will @@ -238,7 +238,7 @@ private long CalculateBlocksMinedPerMiner(int sidechainStartHeight, int sidechai totalBlocks++; } else - this.logger.Trace("A block was mined with an empty script at height '{0}' (the miner probably did not have a wallet at the time.", currentHeight); + this.logger.LogTrace("A block was mined with an empty script at height '{0}' (the miner probably did not have a wallet at the time.", currentHeight); } /* @@ -292,7 +292,7 @@ private List ConstructRecipients(int heightOfRecordedDistributionDepo this.logger.LogDebug(recipientLog.ToString()); */ - this.logger.Info("Reward distribution at main chain height {0} will distribute {1} STRAX between {2} mining keys.", heightOfRecordedDistributionDeposit, totalReward, recipients.Count); + this.logger.LogInformation("Reward distribution at main chain height {0} will distribute {1} STRAX between {2} mining keys.", heightOfRecordedDistributionDeposit, totalReward, recipients.Count); return recipients; } diff --git a/src/Stratis.Features.FederatedPeg/FederatedPegFeature.cs b/src/Stratis.Features.FederatedPeg/FederatedPegFeature.cs index 1e16eb6383..9c2be2b48d 100644 --- a/src/Stratis.Features.FederatedPeg/FederatedPegFeature.cs +++ b/src/Stratis.Features.FederatedPeg/FederatedPegFeature.cs @@ -181,7 +181,7 @@ private void AddComponentStats(StringBuilder benchLog) } catch (Exception e) { - this.logger.Error(e.ToString()); + this.logger.LogError(e.ToString()); } } diff --git a/src/Stratis.Features.FederatedPeg/InputConsolidation/InputConsolidator.cs b/src/Stratis.Features.FederatedPeg/InputConsolidation/InputConsolidator.cs index 5c6c5d4ddd..6580744d9c 100644 --- a/src/Stratis.Features.FederatedPeg/InputConsolidation/InputConsolidator.cs +++ b/src/Stratis.Features.FederatedPeg/InputConsolidation/InputConsolidator.cs @@ -93,17 +93,17 @@ public void StartConsolidation(WalletNeedsConsolidation trigger) if (this.ConsolidationTransactions != null) return; - this.logger.Info("Building consolidation transactions for federation wallet inputs."); + this.logger.LogInformation("Building consolidation transactions for federation wallet inputs."); this.ConsolidationTransactions = this.CreateRequiredConsolidationTransactions(trigger.Amount); if (this.ConsolidationTransactions == null) { - this.logger.Warn("Failed to build condensing transactions."); + this.logger.LogWarning("Failed to build condensing transactions."); return; } - this.logger.Info("Successfully built {0} consolidating transactions.", this.ConsolidationTransactions.Count); + this.logger.LogInformation("Successfully built {0} consolidating transactions.", this.ConsolidationTransactions.Count); } }); @@ -132,18 +132,18 @@ public ConsolidationSignatureResult CombineSignatures(Transaction incomingPartia var builder = new TransactionBuilder(this.network); Transaction oldTransaction = inMemoryTransaction.PartialTransaction; - this.logger.Debug("Attempting to merge signatures for '{0}' and '{1}'.", inMemoryTransaction.PartialTransaction.GetHash(), incomingPartialTransaction.GetHash()); + this.logger.LogDebug("Attempting to merge signatures for '{0}' and '{1}'.", inMemoryTransaction.PartialTransaction.GetHash(), incomingPartialTransaction.GetHash()); Transaction newTransaction = SigningUtils.CheckTemplateAndCombineSignatures(builder, inMemoryTransaction.PartialTransaction, new[] { incomingPartialTransaction }); if (oldTransaction.GetHash() == newTransaction.GetHash()) { // Signing didn't work if the hash is still the same - this.logger.Debug("Signing failed."); + this.logger.LogDebug("Signing failed."); return ConsolidationSignatureResult.Failed(); } - this.logger.Debug("Successfully signed transaction."); + this.logger.LogDebug("Successfully signed transaction."); inMemoryTransaction.PartialTransaction = newTransaction; // NOTE: We don't need to reserve the transaction. The wallet will be at a standstill whilst this is happening. @@ -152,12 +152,12 @@ public ConsolidationSignatureResult CombineSignatures(Transaction incomingPartia if (this.walletManager.ValidateConsolidatingTransaction(inMemoryTransaction.PartialTransaction, true)) { inMemoryTransaction.Status = ConsolidationTransactionStatus.FullySigned; - this.logger.Debug("Consolidation transaction is fully signed. Broadcasting '{0}'", inMemoryTransaction.PartialTransaction.GetHash()); + this.logger.LogDebug("Consolidation transaction is fully signed. Broadcasting '{0}'", inMemoryTransaction.PartialTransaction.GetHash()); this.broadcasterManager.BroadcastTransactionAsync(inMemoryTransaction.PartialTransaction).GetAwaiter().GetResult(); return ConsolidationSignatureResult.Succeeded(inMemoryTransaction.PartialTransaction); } - this.logger.Debug("Consolidation transaction not fully signed yet."); + this.logger.LogDebug("Consolidation transaction not fully signed yet."); return ConsolidationSignatureResult.Succeeded(inMemoryTransaction.PartialTransaction); } @@ -184,7 +184,7 @@ public List CreateRequiredConsolidationTransactions(Mo // We shouldn't be consolidating transactions if we have less than 50 UTXOs to spend. if (unspentOutputs.Count < FederatedPegSettings.MaxInputs) { - this.logger.Info($"Not enough UTXOs '[{unspentOutputs.Count}]' to trigger consolidation transactions."); + this.logger.LogInformation($"Not enough UTXOs '[{unspentOutputs.Count}]' to trigger consolidation transactions."); return null; } @@ -202,7 +202,7 @@ public List CreateRequiredConsolidationTransactions(Mo // Something went wrong building transaction - start over. We will want to build them all from scratch in case wallet has changed state. if (transaction == null) { - this.logger.Warn("Failure building specific consolidating transaction."); + this.logger.LogWarning("Failure building specific consolidating transaction."); return null; } @@ -215,7 +215,7 @@ public List CreateRequiredConsolidationTransactions(Mo // We found a set of 50 that is worth enough so no more consolidation needed. if (oneRound.Sum(x => x.Transaction.Amount) >= amount + FederatedPegSettings.ConsolidationFee) { - this.logger.Info($"Input consolidation threshold reached '{Money.Satoshis(oneRound.Sum(x => x.Transaction.Amount)).ToUnit(MoneyUnit.BTC)}'; consolidation amount '{amount}'."); + this.logger.LogInformation($"Input consolidation threshold reached '{Money.Satoshis(oneRound.Sum(x => x.Transaction.Amount)).ToUnit(MoneyUnit.BTC)}'; consolidation amount '{amount}'."); break; } @@ -262,13 +262,13 @@ private Transaction BuildConsolidatingTransaction(List s Transaction transaction = this.transactionHandler.BuildTransaction(multiSigContext); - this.logger.Info("Consolidating transaction = {0}", transaction.ToString(this.network, RawFormat.BlockExplorer)); + this.logger.LogInformation("Consolidating transaction = {0}", transaction.ToString(this.network, RawFormat.BlockExplorer)); return transaction; } catch (Exception e) { - this.logger.Warn("Exception when building consolidating transaction. Wallet state likely changed before calling: " + e); + this.logger.LogWarning("Exception when building consolidating transaction. Wallet state likely changed before calling: " + e); return null; } } @@ -295,7 +295,7 @@ public void ProcessTransaction(Transaction transaction) if (inMemoryTransaction != null && inMemoryTransaction.Status == ConsolidationTransactionStatus.Partial) { - this.logger.Info("Saw consolidating transaction {0} in mempool, updating its status to FullySigned", transaction.GetHash()); + this.logger.LogInformation("Saw consolidating transaction {0} in mempool, updating its status to FullySigned", transaction.GetHash()); inMemoryTransaction.Status = ConsolidationTransactionStatus.FullySigned; inMemoryTransaction.PartialTransaction = transaction; } @@ -327,7 +327,7 @@ private Task ProcessBlockInternal(ChainedHeaderBlock chainedHeaderBlock, Cancell if (inMemoryTransaction != null) { - this.logger.Info("Saw condensing transaction {0}, updating status to SeenInBlock", + this.logger.LogInformation("Saw condensing transaction {0}, updating status to SeenInBlock", transaction.GetHash()); inMemoryTransaction.Status = ConsolidationTransactionStatus.SeenInBlock; } @@ -346,8 +346,7 @@ private Task ProcessBlockInternal(ChainedHeaderBlock chainedHeaderBlock, Cancell if (!this.walletManager.ValidateConsolidatingTransaction(cTransaction.PartialTransaction)) { // If we find an invalid one, everything will need redoing! - this.logger.Info( - "Consolidation transaction {0} failed validation, resetting InputConsolidator", + this.logger.LogInformation("Consolidation transaction {0} failed validation, resetting InputConsolidator", cTransaction.PartialTransaction.GetHash()); this.ConsolidationTransactions = null; return Task.CompletedTask; diff --git a/src/Stratis.Features.FederatedPeg/PartialTransactionsBehavior.cs b/src/Stratis.Features.FederatedPeg/PartialTransactionsBehavior.cs index 5a68855cb3..cba16e4546 100644 --- a/src/Stratis.Features.FederatedPeg/PartialTransactionsBehavior.cs +++ b/src/Stratis.Features.FederatedPeg/PartialTransactionsBehavior.cs @@ -56,13 +56,13 @@ public override object Clone() protected override void AttachCore() { - this.logger.Debug("Attaching behaviour for {0}", this.AttachedPeer.PeerEndPoint.Address); + this.logger.LogDebug("Attaching behaviour for {0}", this.AttachedPeer.PeerEndPoint.Address); this.AttachedPeer.MessageReceived.Register(this.OnMessageReceivedAsync, true); } protected override void DetachCore() { - this.logger.Debug("Detaching behaviour for {0}", this.AttachedPeer.PeerEndPoint.Address); + this.logger.LogDebug("Detaching behaviour for {0}", this.AttachedPeer.PeerEndPoint.Address); this.AttachedPeer.MessageReceived.Unregister(this.OnMessageReceivedAsync); } @@ -72,7 +72,7 @@ protected override void DetachCore() /// The payload to broadcast. private async Task BroadcastAsync(RequestPartialTransactionPayload payload) { - this.logger.Debug("Broadcasting to {0}", this.AttachedPeer.PeerEndPoint.Address); + this.logger.LogDebug("Broadcasting to {0}", this.AttachedPeer.PeerEndPoint.Address); await this.AttachedPeer.SendMessageAsync(payload).ConfigureAwait(false); } @@ -84,19 +84,19 @@ private async Task OnMessageReceivedAsync(INetworkPeer peer, IncomingMessage mes // Don't process payloads whilst the federation wallet and cross chain store is syncing. if (!this.federationWalletManager.IsSyncedWithChain()) { - this.logger.Debug($"Federation payloads will only be processed once the federation wallet is synced; current height {this.federationWalletManager.WalletTipHeight}"); + this.logger.LogDebug($"Federation payloads will only be processed once the federation wallet is synced; current height {this.federationWalletManager.WalletTipHeight}"); return; } // Is a consolidation request. if (payload.DepositId == RequestPartialTransactionPayload.ConsolidationDepositId) { - this.logger.Debug("Received request to sign consolidation transaction."); + this.logger.LogDebug("Received request to sign consolidation transaction."); await this.HandleConsolidationTransactionRequestAsync(peer, payload); return; } - this.logger.Debug("{0} with deposit Id '{1}' received from '{2}':'{3}'.", nameof(RequestPartialTransactionPayload), payload.DepositId, peer.PeerEndPoint.Address, peer.RemoteSocketAddress); + this.logger.LogDebug("{0} with deposit Id '{1}' received from '{2}':'{3}'.", nameof(Payloads.RequestPartialTransactionPayload), payload.DepositId, peer.PeerEndPoint.Address, peer.RemoteSocketAddress); ICrossChainTransfer[] transfer = await this.crossChainTransferStore.GetAsync(new[] { payload.DepositId }).ConfigureAwait(false); @@ -105,25 +105,25 @@ private async Task OnMessageReceivedAsync(INetworkPeer peer, IncomingMessage mes // on chain and as such the store was not able to sync. if (transfer == null) { - this.logger.Debug("{0}: Unable to retrieve transfers for deposit {1} at this time, the store is not synced.", nameof(this.OnMessageReceivedAsync), payload.DepositId); + this.logger.LogDebug("{0}: Unable to retrieve transfers for deposit {1} at this time, the store is not synced.", nameof(this.OnMessageReceivedAsync), payload.DepositId); return; } if (transfer[0] == null) { - this.logger.Debug("{0}: Deposit {1} does not exist.", nameof(this.OnMessageReceivedAsync), payload.DepositId); + this.logger.LogDebug("{0}: Deposit {1} does not exist.", nameof(this.OnMessageReceivedAsync), payload.DepositId); return; } if (transfer[0].Status != CrossChainTransferStatus.Partial) { - this.logger.Debug("{0}: Deposit {1} is {2}.", nameof(this.OnMessageReceivedAsync), payload.DepositId, transfer[0].Status); + this.logger.LogDebug("{0}: Deposit {1} is {2}.", nameof(this.OnMessageReceivedAsync), payload.DepositId, transfer[0].Status); return; } if (transfer[0].PartialTransaction == null) { - this.logger.Debug("{0}: Deposit {1}, PartialTransaction not found.", nameof(this.OnMessageReceivedAsync), payload.DepositId); + this.logger.LogDebug("{0}: Deposit {1}, PartialTransaction not found.", nameof(this.OnMessageReceivedAsync), payload.DepositId); return; } @@ -133,20 +133,20 @@ private async Task OnMessageReceivedAsync(INetworkPeer peer, IncomingMessage mes if (signedTransaction == null) { - this.logger.Debug("{0}: Deposit {1}, signedTransaction not found.", nameof(this.OnMessageReceivedAsync), payload.DepositId); + this.logger.LogDebug("{0}: Deposit {1}, signedTransaction not found.", nameof(this.OnMessageReceivedAsync), payload.DepositId); return; } if (oldHash != signedTransaction.GetHash()) { - this.logger.Debug("Signed transaction (deposit={0}) to produce {1} from {2}.", payload.DepositId, signedTransaction.GetHash(), oldHash); + this.logger.LogDebug("Signed transaction (deposit={0}) to produce {1} from {2}.", payload.DepositId, signedTransaction.GetHash(), oldHash); // Respond back to the peer that requested a signature. await this.BroadcastAsync(payload.AddPartial(signedTransaction)).ConfigureAwait(false); } else { - this.logger.Debug("The old and signed hash matches '{0}'.", oldHash); + this.logger.LogDebug("The old and signed hash matches '{0}'.", oldHash); } } @@ -156,7 +156,7 @@ private async Task HandleConsolidationTransactionRequestAsync(INetworkPeer peer, if (result.Signed) { - this.logger.Debug("Signed consolidating transaction to produce {0} from {1}", result.TransactionResult.GetHash(), payload.PartialTransaction.GetHash()); + this.logger.LogDebug("Signed consolidating transaction to produce {0} from {1}", result.TransactionResult.GetHash(), payload.PartialTransaction.GetHash()); await this.BroadcastAsync(payload.AddPartial(result.TransactionResult)).ConfigureAwait(false); } } diff --git a/src/Stratis.Features.FederatedPeg/SourceChain/DepositExtractor.cs b/src/Stratis.Features.FederatedPeg/SourceChain/DepositExtractor.cs index a3568bba82..a10c5d42cb 100644 --- a/src/Stratis.Features.FederatedPeg/SourceChain/DepositExtractor.cs +++ b/src/Stratis.Features.FederatedPeg/SourceChain/DepositExtractor.cs @@ -121,7 +121,7 @@ private void ProcessInterFluxBurnRequests(List deposits, int inspectFo { if (inspectForDepositsAtHeight == burnRequest.BlockHeight) { - this.logger.Info($"Processing burn request '{burnRequest.RequestId}' to '{burnRequest.DestinationAddress}' for {new Money(burnRequest.Amount)} STRAX at height {inspectForDepositsAtHeight}."); + this.logger.LogInformation($"Processing burn request '{burnRequest.RequestId}' to '{burnRequest.DestinationAddress}' for {new Money(burnRequest.Amount)} STRAX at height {inspectForDepositsAtHeight}."); Deposit deposit = CreateDeposit(burnRequest, inspectForDepositsAtHeight); if (deposit == null) @@ -150,7 +150,7 @@ private void ProcessInterFluxBurnRequests(List deposits, int inspectFo this.conversionRequestRepository.Save(burnRequest); - this.logger.Info($"Marking burn request '{burnRequest.RequestId}' to '{burnRequest.DestinationAddress}' as processed at height {inspectForDepositsAtHeight}."); + this.logger.LogInformation($"Marking burn request '{burnRequest.RequestId}' to '{burnRequest.DestinationAddress}' as processed at height {inspectForDepositsAtHeight}."); continue; } @@ -166,7 +166,7 @@ private void ProcessInterFluxBurnRequests(List deposits, int inspectFo if (this.depositsBeingProcessedWithinMaturingWindow.Contains(deposit.Id)) { - this.logger.Debug($"Burn request '{burnRequest.RequestId}' is already being processed within the maturity window."); + this.logger.LogDebug($"Burn request '{burnRequest.RequestId}' is already being processed within the maturity window."); continue; } @@ -174,7 +174,7 @@ private void ProcessInterFluxBurnRequests(List deposits, int inspectFo this.depositsBeingProcessedWithinMaturingWindow.Add(deposit.Id); - this.logger.Info($"Re-injecting burn request '{burnRequest.RequestId}' to '{burnRequest.DestinationAddress}' that was processed at {burnRequest.BlockHeight} and will mature at {burnRequest.BlockHeight + requiredConfirmations}."); + this.logger.LogInformation($"Re-injecting burn request '{burnRequest.RequestId}' to '{burnRequest.DestinationAddress}' that was processed at {burnRequest.BlockHeight} and will mature at {burnRequest.BlockHeight + requiredConfirmations}."); continue; } @@ -228,11 +228,11 @@ public Task ExtractDepositFromTransaction(Transaction transaction, int { if (this.federatedPegSettings.IsMainChain && amount < DepositValidationHelper.ConversionTransactionMinimum) { - this.logger.Warn($"Ignoring conversion transaction '{transaction.GetHash()}' with amount {amount} which is below the threshold of {DepositValidationHelper.ConversionTransactionMinimum}."); + this.logger.LogWarning($"Ignoring conversion transaction '{transaction.GetHash()}' with amount {amount} which is below the threshold of {DepositValidationHelper.ConversionTransactionMinimum}."); return Task.FromResult((IDeposit)null); } - this.logger.Info("Received conversion deposit transaction '{0}' for an amount of {1}.", transaction.GetHash(), amount); + this.logger.LogInformation("Received conversion deposit transaction '{0}' for an amount of {1}.", transaction.GetHash(), amount); if (amount > this.federatedPegSettings.NormalDepositThresholdAmount) depositRetrievalType = DepositRetrievalType.ConversionLarge; diff --git a/src/Stratis.Features.FederatedPeg/SourceChain/MaturedBlocksProvider.cs b/src/Stratis.Features.FederatedPeg/SourceChain/MaturedBlocksProvider.cs index d6728ab983..ceea5ba2c9 100644 --- a/src/Stratis.Features.FederatedPeg/SourceChain/MaturedBlocksProvider.cs +++ b/src/Stratis.Features.FederatedPeg/SourceChain/MaturedBlocksProvider.cs @@ -113,7 +113,7 @@ public async Task>> RetrieveD // Don't process blocks below the requested maturity height. if (chainedHeaderBlock.ChainedHeader.Height < maturityHeight) { - this.logger.Debug("{0} below maturity height of {1}.", chainedHeaderBlock.ChainedHeader, maturityHeight); + this.logger.LogDebug("{0} below maturity height of {1}.", chainedHeaderBlock.ChainedHeader, maturityHeight); continue; } @@ -128,7 +128,7 @@ public async Task>> RetrieveD maturedDeposits.AddRange(this.RecallBlockDeposits(chainedHeaderBlock.ChainedHeader.Height - requiredConfirmations, retrievalType)); } - this.logger.Debug("{0} mature deposits retrieved from block '{1}'.", maturedDeposits.Count, chainedHeaderBlock.ChainedHeader); + this.logger.LogDebug("{0} mature deposits retrieved from block '{1}'.", maturedDeposits.Count, chainedHeaderBlock.ChainedHeader); result.Value.Add(new MaturedBlockDepositsModel(new MaturedBlockInfoModel() { @@ -184,13 +184,13 @@ private async Task RecordBlockDepositsAsync(ChainedHeaderBlock chainedHeaderBloc // Already have this recorded? if (this.deposits.TryGetValue(chainedHeaderBlock.ChainedHeader.Height, out BlockDeposits blockDeposits) && blockDeposits.BlockHash == chainedHeaderBlock.ChainedHeader.HashBlock) { - this.logger.Debug("Deposits already recorded for '{0}'.", chainedHeaderBlock.ChainedHeader); + this.logger.LogDebug("Deposits already recorded for '{0}'.", chainedHeaderBlock.ChainedHeader); return; } IReadOnlyList deposits = await this.depositExtractor.ExtractDepositsFromBlock(chainedHeaderBlock.Block, chainedHeaderBlock.ChainedHeader.Height, retrievalTypes).ConfigureAwait(false); - this.logger.Debug("{0} potential deposits extracted from block '{1}'.", deposits.Count, chainedHeaderBlock.ChainedHeader); + this.logger.LogDebug("{0} potential deposits extracted from block '{1}'.", deposits.Count, chainedHeaderBlock.ChainedHeader); this.deposits[chainedHeaderBlock.ChainedHeader.Height] = new BlockDeposits() { diff --git a/src/Stratis.Features.FederatedPeg/TargetChain/CrossChainTransferStore.cs b/src/Stratis.Features.FederatedPeg/TargetChain/CrossChainTransferStore.cs index bed70e9c11..2a8bd18b5c 100644 --- a/src/Stratis.Features.FederatedPeg/TargetChain/CrossChainTransferStore.cs +++ b/src/Stratis.Features.FederatedPeg/TargetChain/CrossChainTransferStore.cs @@ -224,7 +224,7 @@ private ICrossChainTransfer[] ValidateCrossChainTransfers(ICrossChainTransfer[] List<(Transaction transaction, IWithdrawal withdrawal)> walletData = this.federationWalletManager.FindWithdrawalTransactions(partialTransfer.DepositTransactionId); - this.logger.Trace("DepositTransactionId:{0}; {1}:{2}", partialTransfer.DepositTransactionId, nameof(walletData), walletData.Count); + this.logger.LogTrace("DepositTransactionId:{0}; {1}:{2}", partialTransfer.DepositTransactionId, nameof(walletData), walletData.Count); if (walletData.Count == 1 && this.ValidateTransaction(walletData[0].transaction)) { @@ -246,7 +246,7 @@ private ICrossChainTransfer[] ValidateCrossChainTransfers(ICrossChainTransfer[] continue; } - this.logger.Debug("Templates don't match for {0} and {1}.", walletTran.GetHash(), partialTransfer.PartialTransaction.GetHash()); + this.logger.LogDebug("Templates don't match for {0} and {1}.", walletTran.GetHash(), partialTransfer.PartialTransaction.GetHash()); } // The chain may have been rewound so that this transaction or its UTXO's have been lost. @@ -254,14 +254,14 @@ private ICrossChainTransfer[] ValidateCrossChainTransfers(ICrossChainTransfer[] if (partialTransfer.DepositHeight < newChainATip) newChainATip = partialTransfer.DepositHeight ?? newChainATip; - this.logger.Debug("Setting DepositId {0} to Suspended", partialTransfer.DepositTransactionId); + this.logger.LogDebug("Setting DepositId {0} to Suspended", partialTransfer.DepositTransactionId); tracker.SetTransferStatus(partialTransfer, CrossChainTransferStatus.Suspended); } if (tracker.Count == 0) { - this.logger.Trace("(-)[NO_CHANGES_IN_TRACKER]"); + this.logger.LogTrace("(-)[NO_CHANGES_IN_TRACKER]"); return crossChainTransfers; } @@ -314,7 +314,7 @@ private ICrossChainTransfer[] ValidateCrossChainTransfers(ICrossChainTransfer[] /// Short reason/context code of failure. private void RollbackAndThrowTransactionError(DBreeze.Transactions.Transaction dbreezeTransaction, Exception exception, string reason = "FAILED_TRANSACTION") { - this.logger.Error("Error during database update: {0}, reason: {1}", exception.Message, reason); + this.logger.LogError("Error during database update: {0}, reason: {1}", exception.Message, reason); dbreezeTransaction.Rollback(); throw exception; @@ -373,7 +373,7 @@ public void RejectTransfer(ICrossChainTransfer crossChainTransfer) } catch (Exception err) { - this.logger.Error("An error occurred when processing deposits {0}", err); + this.logger.LogError("An error occurred when processing deposits {0}", err); this.RollbackAndThrowTransactionError(dbreezeTransaction, err, "REJECT_ERROR"); } @@ -400,13 +400,13 @@ public Task RecordLatestMatureDepositsAsync(IL if (maturedBlockDeposits.Count == 0 || maturedBlockDeposits.First().BlockInfo.BlockHeight != this.NextMatureDepositHeight) { - this.logger.Debug($"No viable blocks to process; {nameof(maturedBlockDeposits)}={maturedBlockDeposits.Count};{nameof(this.NextMatureDepositHeight)}={this.NextMatureDepositHeight}"); + this.logger.LogDebug($"No viable blocks to process; {nameof(maturedBlockDeposits)}={maturedBlockDeposits.Count};{nameof(this.NextMatureDepositHeight)}={this.NextMatureDepositHeight}"); return new RecordLatestMatureDepositsResult().Succeeded(); } if (maturedBlockDeposits.Last().BlockInfo.BlockHeight != this.NextMatureDepositHeight + maturedBlockDeposits.Count - 1) { - this.logger.Debug("(-)[DUPLICATE_BLOCKS]:true"); + this.logger.LogDebug("(-)[DUPLICATE_BLOCKS]:true"); return new RecordLatestMatureDepositsResult().Succeeded(); } @@ -417,7 +417,7 @@ public Task RecordLatestMatureDepositsAsync(IL { this.NextMatureDepositHeight += maturedBlockDeposits.Count; - this.logger.Debug("(-)[NO_DEPOSITS]:true"); + this.logger.LogDebug("(-)[NO_DEPOSITS]:true"); return new RecordLatestMatureDepositsResult().Succeeded(); } @@ -428,8 +428,8 @@ public Task RecordLatestMatureDepositsAsync(IL if (!this.Synchronize()) return; - this.logger.Info($"{maturedBlockDeposits.Count} blocks received, containing a total of {maturedBlockDeposits.SelectMany(d => d.Deposits).Where(a => a.Amount > 0).Count()} deposits."); - this.logger.Info($"Block Range : {maturedBlockDeposits.Min(a => a.BlockInfo.BlockHeight)} to {maturedBlockDeposits.Max(a => a.BlockInfo.BlockHeight)}."); + this.logger.LogInformation($"{maturedBlockDeposits.Count} blocks received, containing a total of {maturedBlockDeposits.SelectMany(d => d.Deposits).Where(a => a.Amount > 0).Count()} deposits."); + this.logger.LogInformation($"Block Range : {maturedBlockDeposits.Min(a => a.BlockInfo.BlockHeight)} to {maturedBlockDeposits.Max(a => a.BlockInfo.BlockHeight)}."); foreach (MaturedBlockDepositsModel maturedDeposit in maturedBlockDeposits) { @@ -445,7 +445,7 @@ public Task RecordLatestMatureDepositsAsync(IL if (!this.federationWalletManager.IsFederationWalletActive()) { - this.logger.Error("The store can't persist mature deposits while the federation is inactive."); + this.logger.LogError("The store can't persist mature deposits while the federation is inactive."); continue; } @@ -492,14 +492,14 @@ public Task RecordLatestMatureDepositsAsync(IL if (invalidRecipient) { - this.logger.Info("Invalid recipient."); + this.logger.LogInformation("Invalid recipient."); status = CrossChainTransferStatus.Rejected; } else if ((tracker.Count(t => t.Value == CrossChainTransferStatus.Partial) + this.depositsIdsByStatus[CrossChainTransferStatus.Partial].Count) >= this.settings.MaximumPartialTransactionThreshold) { haveSuspendedTransfers = true; - this.logger.Warn($"Partial transaction limit of {this.settings.MaximumPartialTransactionThreshold} reached, processing of deposits will continue once the partial transaction count falls below this value."); + this.logger.LogWarning($"Partial transaction limit of {this.settings.MaximumPartialTransactionThreshold} reached, processing of deposits will continue once the partial transaction count falls below this value."); } else { @@ -512,7 +512,7 @@ public Task RecordLatestMatureDepositsAsync(IL if (!this.ValidateTransaction(transaction)) { - this.logger.Info("Suspending transfer for deposit '{0}' to retry invalid transaction later.", deposit.Id); + this.logger.LogInformation("Suspending transfer for deposit '{0}' to retry invalid transaction later.", deposit.Id); this.federationWalletManager.RemoveWithdrawalTransactions(deposit.Id); haveSuspendedTransfers = true; @@ -526,27 +526,27 @@ public Task RecordLatestMatureDepositsAsync(IL } else { - this.logger.Info("Unable to build withdrawal transaction, suspending."); + this.logger.LogInformation("Unable to build withdrawal transaction, suspending."); haveSuspendedTransfers = true; } } } else { - this.logger.Info("Suspended flag set: '{0}'", deposit); + this.logger.LogInformation("Suspended flag set: '{0}'", deposit); } if (transfers[i] == null || transaction == null) { transfers[i] = new CrossChainTransfer(status, deposit.Id, scriptPubKey, deposit.Amount, maturedDeposit.BlockInfo.BlockHeight, transaction, null, null); tracker.SetTransferStatus(transfers[i]); - this.logger.Debug("Set {0} to {1}.", transfers[i]?.DepositTransactionId, status); + this.logger.LogDebug("Set {0} to {1}.", transfers[i]?.DepositTransactionId, status); } else { transfers[i].SetPartialTransaction(transaction); tracker.SetTransferStatus(transfers[i], CrossChainTransferStatus.Partial); - this.logger.Debug("Set {0} to Partial.", transfers[i]?.DepositTransactionId); + this.logger.LogDebug("Set {0} to Partial.", transfers[i]?.DepositTransactionId); } } @@ -579,7 +579,7 @@ public Task RecordLatestMatureDepositsAsync(IL } catch (Exception err) { - this.logger.Error("An error occurred when processing deposits {0}", err); + this.logger.LogError("An error occurred when processing deposits {0}", err); // Undo reserved UTXO's. if (walletUpdated) @@ -629,55 +629,55 @@ public Transaction MergeTransactionSignatures(uint256 depositId, Transaction[] p if (transfer == null) { - this.logger.Debug("(-)[MERGE_NOT_FOUND]:null"); + this.logger.LogDebug("(-)[MERGE_NOT_FOUND]:null"); return null; } if (transfer.Status != CrossChainTransferStatus.Partial) { - this.logger.Debug("(-)[MERGE_BAD_STATUS]:{0}={1}", nameof(transfer.Status), transfer.Status); + this.logger.LogDebug("(-)[MERGE_BAD_STATUS]:{0}={1}", nameof(transfer.Status), transfer.Status); return transfer.PartialTransaction; } try { - this.logger.Debug("Partial Transaction inputs:{0}", partialTransactions[0].Inputs.Count); - this.logger.Debug("Partial Transaction outputs:{0}", partialTransactions[0].Outputs.Count); + this.logger.LogDebug("Partial Transaction inputs:{0}", partialTransactions[0].Inputs.Count); + this.logger.LogDebug("Partial Transaction outputs:{0}", partialTransactions[0].Outputs.Count); for (int i = 0; i < partialTransactions[0].Inputs.Count; i++) { TxIn input = partialTransactions[0].Inputs[i]; - this.logger.Debug("Partial Transaction Input N:{0} : Hash:{1}", input.PrevOut.N, input.PrevOut.Hash); + this.logger.LogDebug("Partial Transaction Input N:{0} : Hash:{1}", input.PrevOut.N, input.PrevOut.Hash); } for (int i = 0; i < partialTransactions[0].Outputs.Count; i++) { TxOut output = partialTransactions[0].Outputs[i]; - this.logger.Debug("Partial Transaction Output Value:{0} : ScriptPubKey:{1}", output.Value, output.ScriptPubKey); + this.logger.LogDebug("Partial Transaction Output Value:{0} : ScriptPubKey:{1}", output.Value, output.ScriptPubKey); } - this.logger.Debug("Transfer Partial Transaction inputs:{0}", transfer.PartialTransaction.Inputs.Count); - this.logger.Debug("Transfer Partial Transaction outputs:{0}", transfer.PartialTransaction.Outputs.Count); + this.logger.LogDebug("Transfer Partial Transaction inputs:{0}", transfer.PartialTransaction.Inputs.Count); + this.logger.LogDebug("Transfer Partial Transaction outputs:{0}", transfer.PartialTransaction.Outputs.Count); for (int i = 0; i < transfer.PartialTransaction.Inputs.Count; i++) { TxIn transferInput = transfer.PartialTransaction.Inputs[i]; - this.logger.Debug("Transfer Partial Transaction Input N:{0} : Hash:{1}", transferInput.PrevOut.N, transferInput.PrevOut.Hash); + this.logger.LogDebug("Transfer Partial Transaction Input N:{0} : Hash:{1}", transferInput.PrevOut.N, transferInput.PrevOut.Hash); } for (int i = 0; i < transfer.PartialTransaction.Outputs.Count; i++) { TxOut transferOutput = transfer.PartialTransaction.Outputs[i]; - this.logger.Debug("Transfer Partial Transaction Output Value:{0} : ScriptPubKey:{1}", transferOutput.Value, transferOutput.ScriptPubKey); + this.logger.LogDebug("Transfer Partial Transaction Output Value:{0} : ScriptPubKey:{1}", transferOutput.Value, transferOutput.ScriptPubKey); } } catch (Exception err) { - this.logger.Debug("Failed to log transactions: {0}.", err.Message); + this.logger.LogDebug("Failed to log transactions: {0}.", err.Message); } - this.logger.Debug("Merging signatures for deposit : {0}", depositId); + this.logger.LogDebug("Merging signatures for deposit : {0}", depositId); var builder = new TransactionBuilder(this.network); Transaction oldTransaction = transfer.PartialTransaction; @@ -689,7 +689,7 @@ public Transaction MergeTransactionSignatures(uint256 depositId, Transaction[] p // We will finish dealing with the request here if an invalid signature is sent. // The incoming partial transaction will not have the same inputs / outputs as what our node has generated // so would have failed CrossChainTransfer.TemplatesMatch() and leave through here. - this.logger.Debug("(-)[MERGE_UNCHANGED_TX_HASHES_MATCH]"); + this.logger.LogDebug("(-)[MERGE_UNCHANGED_TX_HASHES_MATCH]"); return transfer.PartialTransaction; } @@ -704,13 +704,13 @@ public Transaction MergeTransactionSignatures(uint256 depositId, Transaction[] p if (this.ValidateTransaction(transfer.PartialTransaction, true)) { - this.logger.Debug("Deposit: {0} collected enough signatures and is FullySigned", transfer.DepositTransactionId); + this.logger.LogDebug("Deposit: {0} collected enough signatures and is FullySigned", transfer.DepositTransactionId); transfer.SetStatus(CrossChainTransferStatus.FullySigned); this.signals.Publish(new CrossChainTransferTransactionFullySigned(transfer)); } else { - this.logger.Debug("Deposit: {0} did not collect enough signatures and is Partial", transfer.DepositTransactionId); + this.logger.LogDebug("Deposit: {0} did not collect enough signatures and is Partial", transfer.DepositTransactionId); } this.PutTransfer(dbreezeTransaction, transfer); @@ -722,7 +722,7 @@ public Transaction MergeTransactionSignatures(uint256 depositId, Transaction[] p } catch (Exception err) { - this.logger.Error("Error: {0} ", err); + this.logger.LogError("Error: {0} ", err); // Restore expected store state in case the calling code retries / continues using the store. transfer.SetPartialTransaction(oldTransaction); @@ -749,7 +749,7 @@ public Transaction MergeTransactionSignatures(uint256 depositId, Transaction[] p private void Put(List blocks, Dictionary chainedHeadersSnapshot) { if (blocks.Count == 0) - this.logger.Trace("(-)[NO_BLOCKS]:0"); + this.logger.LogTrace("(-)[NO_BLOCKS]:0"); Dictionary transferLookup; Dictionary allWithdrawals; @@ -771,7 +771,7 @@ private void Put(List blocks, Dictionary chainedH // Exiting here and saving the tip after the sync. this.TipHashAndHeight = chainedHeadersSnapshot[blocks.Last().GetHash()]; - this.logger.Trace("(-)[NO_DEPOSIT_IDS]"); + this.logger.LogTrace("(-)[NO_DEPOSIT_IDS]"); return; } @@ -856,7 +856,7 @@ private void RewindIfRequiredLocked() { if (this.TipHashAndHeight == null) { - this.logger.Trace("(-)[CCTS_TIP_NOT_SET]"); + this.logger.LogTrace("(-)[CCTS_TIP_NOT_SET]"); return; } @@ -865,7 +865,7 @@ private void RewindIfRequiredLocked() // Indicates that the CCTS is synchronized with the Federation Wallet. if (this.TipHashAndHeight.HashBlock == tipToChase.Hash) { - this.logger.Trace("(-)[SYNCHRONIZED]"); + this.logger.LogTrace("(-)[SYNCHRONIZED]"); return; } @@ -953,8 +953,8 @@ private bool Synchronize() { if (this.TipHashAndHeight == null) { - this.logger.Error("Synchronization failed as the store's tip is null."); - this.logger.Trace("(-)[CCTS_TIP_NOT_SET]:false"); + this.logger.LogError("Synchronization failed as the store's tip is null."); + this.logger.LogTrace("(-)[CCTS_TIP_NOT_SET]:false"); return false; } @@ -963,15 +963,15 @@ private bool Synchronize() // Check if the federation wallet's tip is on chain, if not exit. if (this.chainIndexer.GetHeader(federationWalletTip.Hash) == null) { - this.logger.Debug("Synchronization failed as the federation wallet tip is not on chain; {0}='{1}', {2}='{3}'", nameof(this.chainIndexer.Tip), this.chainIndexer.Tip, nameof(federationWalletTip), federationWalletTip); - this.logger.Trace("(-)[FED_WALLET_TIP_NOT_ONCHAIN]:false"); + this.logger.LogDebug("Synchronization failed as the federation wallet tip is not on chain; {0}='{1}', {2}='{3}'", nameof(this.chainIndexer.Tip), this.chainIndexer.Tip, nameof(federationWalletTip), federationWalletTip); + this.logger.LogTrace("(-)[FED_WALLET_TIP_NOT_ONCHAIN]:false"); return false; } // If the federation wallet tip matches the store's tip, exit. if (federationWalletTip.Hash == this.TipHashAndHeight.HashBlock) { - this.logger.Trace("(-)[SYNCHRONIZED]:true"); + this.logger.LogTrace("(-)[SYNCHRONIZED]:true"); return true; } @@ -986,7 +986,7 @@ private bool Synchronize() } catch (Exception ex) { - this.logger.Error($"An error occurred whilst synchronizing the store: {ex}."); + this.logger.LogError($"An error occurred whilst synchronizing the store: {ex}."); throw ex; } } @@ -1041,7 +1041,7 @@ private bool SynchronizeBatch() { // If the federation tip is found to be not on chain, we need to throw an // exception to ensure that we exit the synchronization process. - this.logger.Trace("(-)[FEDERATION_WALLET_TIP_NOT_ON CHAIN]:{0}='{1}', {2}='{3}'", nameof(this.chainIndexer.Tip), this.chainIndexer.Tip, nameof(federationWalletTip), federationWalletTip); + this.logger.LogTrace("(-)[FEDERATION_WALLET_TIP_NOT_ON CHAIN]:{0}='{1}', {2}='{3}'", nameof(this.chainIndexer.Tip), this.chainIndexer.Tip, nameof(federationWalletTip), federationWalletTip); throw new FederationWalletTipNotOnChainException(); } @@ -1070,7 +1070,7 @@ private bool SynchronizeBatch() { Block lastBlock = blocks[availableBlocks - 1]; this.Put(blocks.GetRange(0, availableBlocks), chainedHeadersSnapshot); - this.logger.Info("Synchronized {0} blocks with cross-chain store to advance tip to block {1}", availableBlocks, this.TipHashAndHeight?.Height); + this.logger.LogInformation("Synchronized {0} blocks with cross-chain store to advance tip to block {1}", availableBlocks, this.TipHashAndHeight?.Height); } bool done = availableBlocks < SynchronizationBatchSize; @@ -1327,7 +1327,7 @@ private StatusChangeTracker OnDeleteBlocks(DBreeze.Transactions.Transaction dbre { // Transaction is no longer seen and the FederationWalletManager is going to remove the transaction anyhow // So don't prolong - just set to Suspended now. - this.logger.Debug("Setting DepositId {0} to Suspended", transfer.DepositTransactionId); + this.logger.LogDebug("Setting DepositId {0} to Suspended", transfer.DepositTransactionId); tracker.SetTransferStatus(transfer, CrossChainTransferStatus.Suspended); // Write the transfer status to the database. @@ -1488,7 +1488,7 @@ private void AddComponentStats(StringBuilder benchLog) { benchLog.AppendLine("--- Pending Withdrawals ---"); benchLog.AppendLine("Failed to retrieve data"); - this.logger.Error("Exception occurred while getting pending withdrawals: '{0}'.", exception.ToString()); + this.logger.LogError("Exception occurred while getting pending withdrawals: '{0}'.", exception.ToString()); } } @@ -1515,7 +1515,7 @@ public int DeleteSuspendedTransfers() { this.DeleteTransfer(dbreezeTransaction, transfer); this.depositsIdsByStatus[CrossChainTransferStatus.Suspended].Clear(); - this.logger.Debug($"Suspended transfer with deposit id '{transfer.DepositTransactionId}' deleted."); + this.logger.LogDebug($"Suspended transfer with deposit id '{transfer.DepositTransactionId}' deleted."); } dbreezeTransaction.Commit(); diff --git a/src/Stratis.Features.FederatedPeg/TargetChain/FederatedPegBroadcaster.cs b/src/Stratis.Features.FederatedPeg/TargetChain/FederatedPegBroadcaster.cs index 02dedb96e4..a1bc00b2c1 100644 --- a/src/Stratis.Features.FederatedPeg/TargetChain/FederatedPegBroadcaster.cs +++ b/src/Stratis.Features.FederatedPeg/TargetChain/FederatedPegBroadcaster.cs @@ -31,13 +31,13 @@ public Task BroadcastAsync(Payload payload) { IEnumerable connectedPeers = this.connectionManager.ConnectedPeers.Where(peer => (peer?.IsConnected ?? false) && this.federatedPegSettings.FederationNodeIpAddresses.Contains(peer.PeerEndPoint.Address)); - this.logger.Trace($"Sending {payload.GetType()} to {connectedPeers.Count()} peers."); + this.logger.LogTrace($"Sending {payload.GetType()} to {connectedPeers.Count()} peers."); Parallel.ForEach(connectedPeers, async (INetworkPeer peer) => { try { - this.logger.Trace($"Sending {payload.GetType()} to {peer.RemoteSocketAddress}"); + this.logger.LogTrace($"Sending {payload.GetType()} to {peer.RemoteSocketAddress}"); await peer.SendMessageAsync(payload).ConfigureAwait(false); } catch (OperationCanceledException) @@ -45,7 +45,7 @@ public Task BroadcastAsync(Payload payload) } catch (Exception ex) { - this.logger.Error($"Error sending {payload.GetType().Name} to {peer.PeerEndPoint.Address}:{ex.ToString()}"); + this.logger.LogError($"Error sending {payload.GetType().Name} to {peer.PeerEndPoint.Address}:{ex.ToString()}"); } }); diff --git a/src/Stratis.Features.FederatedPeg/TargetChain/MaturedBlocksSyncManager.cs b/src/Stratis.Features.FederatedPeg/TargetChain/MaturedBlocksSyncManager.cs index 43f6dd808d..e80cd98f6d 100644 --- a/src/Stratis.Features.FederatedPeg/TargetChain/MaturedBlocksSyncManager.cs +++ b/src/Stratis.Features.FederatedPeg/TargetChain/MaturedBlocksSyncManager.cs @@ -122,37 +122,37 @@ protected async Task SyncDepositsAsync() // First ensure that the federation wallet is active. if (!this.federationWalletManager.IsFederationWalletActive()) { - this.logger.Info("The CCTS will start processing deposits once the federation wallet has been activated."); + this.logger.LogInformation("The CCTS will start processing deposits once the federation wallet has been activated."); return true; } // Then ensure that the node is out of IBD. if (this.initialBlockDownloadState.IsInitialBlockDownload()) { - this.logger.Info("The CCTS will start processing deposits once the node is out of IBD."); + this.logger.LogInformation("The CCTS will start processing deposits once the node is out of IBD."); return true; } // Then ensure that the federation wallet is synced with the chain. if (!this.federationWalletManager.IsSyncedWithChain()) { - this.logger.Info($"The CCTS will start processing deposits once the federation wallet is synced with the chain; height {this.federationWalletManager.WalletTipHeight}"); + this.logger.LogInformation($"The CCTS will start processing deposits once the federation wallet is synced with the chain; height {this.federationWalletManager.WalletTipHeight}"); return true; } - this.logger.Info($"Requesting deposits from counterchain node."); + this.logger.LogInformation($"Requesting deposits from counterchain node."); SerializableResult> matureBlockDeposits = await this.federationGatewayClient.GetMaturedBlockDepositsAsync(this.crossChainTransferStore.NextMatureDepositHeight, this.nodeLifetime.ApplicationStopping).ConfigureAwait(false); if (matureBlockDeposits == null) { - this.logger.Debug("Failed to fetch normal deposits from counter chain node; {0} didn't respond.", this.federationGatewayClient.EndpointUrl); + this.logger.LogDebug("Failed to fetch normal deposits from counter chain node; {0} didn't respond.", this.federationGatewayClient.EndpointUrl); return true; } if (matureBlockDeposits.Value == null) { - this.logger.Debug("Failed to fetch normal deposits from counter chain node; {0} didn't reply with any deposits; Message: {1}", this.federationGatewayClient.EndpointUrl, matureBlockDeposits.Message ?? "none"); + this.logger.LogDebug("Failed to fetch normal deposits from counter chain node; {0} didn't reply with any deposits; Message: {1}", this.federationGatewayClient.EndpointUrl, matureBlockDeposits.Message ?? "none"); return true; } @@ -164,7 +164,7 @@ private async Task ProcessMatureBlockDepositsAsync(SerializableResult ProcessMatureBlockDepositsAsync(SerializableResult ProcessMatureBlockDepositsAsync(SerializableResult(); if (maturedBlockDeposit.Deposits.Count > 0) - this.logger.Debug("Matured deposit count for block {0} height {1}: {2}.", maturedBlockDeposit.BlockInfo.BlockHash, maturedBlockDeposit.BlockInfo.BlockHeight, maturedBlockDeposit.Deposits.Count); + this.logger.LogDebug("Matured deposit count for block {0} height {1}: {2}.", maturedBlockDeposit.BlockInfo.BlockHash, maturedBlockDeposit.BlockInfo.BlockHeight, maturedBlockDeposit.Deposits.Count); foreach (IDeposit potentialConversionTransaction in maturedBlockDeposit.Deposits) { @@ -196,24 +196,24 @@ private async Task ProcessMatureBlockDepositsAsync(SerializableResult ProcessMatureBlockDepositsAsync(SerializableResult= potentialConversionTransaction.Amount) { - this.logger.Warn("Conversion transaction '{0}' is no longer large enough to cover the fee.", potentialConversionTransaction.Id); + this.logger.LogWarning("Conversion transaction '{0}' is no longer large enough to cover the fee.", potentialConversionTransaction.Id); continue; } // We insert the fee distribution as a deposit to be processed, albeit with a special address. // Deposits with this address as their destination will be distributed between the multisig members. // Note that it will be actioned immediately as a matured deposit. - this.logger.Info("Adding conversion fee distribution for transaction '{0}' to deposit list.", potentialConversionTransaction.Id); + this.logger.LogInformation("Adding conversion fee distribution for transaction '{0}' to deposit list.", potentialConversionTransaction.Id); // Instead of being a conversion deposit, the fee distribution is translated to its non-conversion equivalent. DepositRetrievalType depositType = DepositRetrievalType.Small; @@ -270,7 +270,7 @@ private async Task ProcessMatureBlockDepositsAsync(SerializableResult ProcessMatureBlockDepositsAsync(SerializableResult partialtransfers = this.crossChainTransferStore.GetTransfersByStatus(new[] { CrossChainTransferStatus.Partial }, true); - this.logger.Info($"Requesting partial templates for {partialtransfers.Count()} transfers."); + this.logger.LogInformation($"Requesting partial templates for {partialtransfers.Count()} transfers."); foreach (ICrossChainTransfer transfer in partialtransfers) { await this.federatedPegBroadcaster.BroadcastAsync(new RequestPartialTransactionPayload(transfer.DepositTransactionId).AddPartial(transfer.PartialTransaction)).ConfigureAwait(false); - this.logger.Debug("Partial template requested for deposit Id '{0}'", transfer.DepositTransactionId); + this.logger.LogDebug("Partial template requested for deposit Id '{0}'", transfer.DepositTransactionId); } // If we don't have any broadcastable transactions, check if we have any consolidating transactions to sign. @@ -98,7 +98,7 @@ public async Task BroadcastPartialTransactionsAsync() if (toSign != null) { await this.federatedPegBroadcaster.BroadcastAsync(new RequestPartialTransactionPayload(RequestPartialTransactionPayload.ConsolidationDepositId).AddPartial(toSign.PartialTransaction)).ConfigureAwait(false); - this.logger.Debug("Partial consolidating transaction requested for '{0}'.", toSign.PartialTransaction.GetHash()); + this.logger.LogDebug("Partial consolidating transaction requested for '{0}'.", toSign.PartialTransaction.GetHash()); } } } diff --git a/src/Stratis.Features.FederatedPeg/TargetChain/SignedMultisigTransactionBroadcaster.cs b/src/Stratis.Features.FederatedPeg/TargetChain/SignedMultisigTransactionBroadcaster.cs index d43cd1b565..fd8406d060 100644 --- a/src/Stratis.Features.FederatedPeg/TargetChain/SignedMultisigTransactionBroadcaster.cs +++ b/src/Stratis.Features.FederatedPeg/TargetChain/SignedMultisigTransactionBroadcaster.cs @@ -88,7 +88,7 @@ public async Task BroadcastFullySigned if (fullySignedTransfers.Length == 0) { - this.logger.Debug("There are no fully signed transactions to broadcast."); + this.logger.LogDebug("There are no fully signed transactions to broadcast."); return new SignedMultisigTransactionBroadcastResult() { Message = "There are no fully signed transactions to broadcast." }; } @@ -113,12 +113,12 @@ private async Task BroadcastFullyS TxMempoolInfo txMempoolInfo = await this.mempoolManager.InfoAsync(crossChainTransfer.PartialTransaction.GetHash()).ConfigureAwait(false); if (txMempoolInfo != null) { - this.logger.Info("Deposit '{0}' already in the mempool.", crossChainTransfer.DepositTransactionId); + this.logger.LogInformation("Deposit '{0}' already in the mempool.", crossChainTransfer.DepositTransactionId); transferItem.ItemMessage = $"Deposit '{crossChainTransfer.DepositTransactionId}' already in the mempool."; return transferItem; } - this.logger.Info("Broadcasting deposit '{0}', a signed multisig transaction '{1}' to the network.", crossChainTransfer.DepositTransactionId, crossChainTransfer.PartialTransaction.GetHash()); + this.logger.LogInformation("Broadcasting deposit '{0}', a signed multisig transaction '{1}' to the network.", crossChainTransfer.DepositTransactionId, crossChainTransfer.PartialTransaction.GetHash()); await this.broadcasterManager.BroadcastTransactionAsync(crossChainTransfer.PartialTransaction).ConfigureAwait(false); @@ -133,7 +133,7 @@ private async Task BroadcastFullyS if (transactionBroadCastEntry.TransactionBroadcastState == TransactionBroadcastState.CantBroadcast && !CrossChainTransferStore.IsMempoolErrorRecoverable(transactionBroadCastEntry.MempoolError)) { - this.logger.Warn("Deposit '{0}' rejected: '{1}'.", crossChainTransfer.DepositTransactionId, transactionBroadCastEntry.ErrorMessage); + this.logger.LogWarning("Deposit '{0}' rejected: '{1}'.", crossChainTransfer.DepositTransactionId, transactionBroadCastEntry.ErrorMessage); this.crossChainTransferStore.RejectTransfer(crossChainTransfer); transferItem.ItemMessage = $"Deposit '{crossChainTransfer.DepositTransactionId}' rejected: '{transactionBroadCastEntry.ErrorMessage}'."; return transferItem; diff --git a/src/Stratis.Features.FederatedPeg/TargetChain/WithdrawalTransactionBuilder.cs b/src/Stratis.Features.FederatedPeg/TargetChain/WithdrawalTransactionBuilder.cs index 68aa890306..6576252630 100644 --- a/src/Stratis.Features.FederatedPeg/TargetChain/WithdrawalTransactionBuilder.cs +++ b/src/Stratis.Features.FederatedPeg/TargetChain/WithdrawalTransactionBuilder.cs @@ -65,7 +65,7 @@ public Transaction BuildWithdrawalTransaction(int blockHeight, uint256 depositId { try { - this.logger.Debug("BuildDeterministicTransaction depositId(opReturnData)={0}; recipient.ScriptPubKey={1}; recipient.Amount={2}; height={3}", depositId, recipient.ScriptPubKey, recipient.Amount, blockHeight); + this.logger.LogDebug("BuildDeterministicTransaction depositId(opReturnData)={0}; recipient.ScriptPubKey={1}; recipient.Amount={2}; height={3}", depositId, recipient.ScriptPubKey, recipient.Amount, blockHeight); // Build the multisig transaction template. uint256 opReturnData = depositId; @@ -100,7 +100,7 @@ public Transaction BuildWithdrawalTransaction(int blockHeight, uint256 depositId if (recipient.ScriptPubKey == this.conversionTransactionFeeDistributionScriptPubKey) { - this.logger.Debug("Generating recipient list for conversion transaction fee distribution."); + this.logger.LogDebug("Generating recipient list for conversion transaction fee distribution."); multiSigContext.Recipients = this.distributionManager.DistributeToMultisigNodes(blockHeight, recipient.WithPaymentReducedByFee(FederatedPegSettings.CrossChainTransferFee).Amount); } @@ -112,9 +112,9 @@ public Transaction BuildWithdrawalTransaction(int blockHeight, uint256 depositId if (coins.Count > FederatedPegSettings.MaxInputs) { - this.logger.Debug("Too many inputs. Triggering the consolidation process."); + this.logger.LogDebug("Too many inputs. Triggering the consolidation process."); this.signals.Publish(new WalletNeedsConsolidation(recipient.Amount)); - this.logger.Trace("(-)[CONSOLIDATING_INPUTS]"); + this.logger.LogTrace("(-)[CONSOLIDATING_INPUTS]"); return null; } @@ -124,7 +124,7 @@ public Transaction BuildWithdrawalTransaction(int blockHeight, uint256 depositId // Build the transaction. Transaction transaction = this.federationWalletTransactionHandler.BuildTransaction(multiSigContext); - this.logger.Debug("transaction = {0}", transaction.ToString(this.network, RawFormat.BlockExplorer)); + this.logger.LogDebug("transaction = {0}", transaction.ToString(this.network, RawFormat.BlockExplorer)); return transaction; } @@ -134,15 +134,15 @@ public Transaction BuildWithdrawalTransaction(int blockHeight, uint256 depositId (walletException.Message == FederationWalletTransactionHandler.NoSpendableTransactionsMessage || walletException.Message == FederationWalletTransactionHandler.NotEnoughFundsMessage)) { - this.logger.Warn("Not enough spendable transactions in the wallet. Should be resolved when a pending transaction is included in a block."); + this.logger.LogWarning("Not enough spendable transactions in the wallet. Should be resolved when a pending transaction is included in a block."); } else { - this.logger.Error("Could not create transaction for deposit {0}: {1}", depositId, error.Message); + this.logger.LogError("Could not create transaction for deposit {0}: {1}", depositId, error.Message); } } - this.logger.Trace("(-)[FAIL]"); + this.logger.LogTrace("(-)[FAIL]"); return null; } } diff --git a/src/Stratis.Features.FederatedPeg/Wallet/BlockQueueProcessor.cs b/src/Stratis.Features.FederatedPeg/Wallet/BlockQueueProcessor.cs index 45670d78b4..651298aeb4 100644 --- a/src/Stratis.Features.FederatedPeg/Wallet/BlockQueueProcessor.cs +++ b/src/Stratis.Features.FederatedPeg/Wallet/BlockQueueProcessor.cs @@ -52,7 +52,7 @@ private async Task OnProcessBlockAsync(Block block, CancellationToken cancellati { long currentBlockQueueSize = Interlocked.Add(ref this.blocksQueueSize, -block.BlockSize.Value); - this.logger.Debug("Block '{0}' queued for processing. Queue size changed to {1} bytes.", block.GetHash(), currentBlockQueueSize); + this.logger.LogDebug("Block '{0}' queued for processing. Queue size changed to {1} bytes.", block.GetHash(), currentBlockQueueSize); await this.callback(block, cancellationToken).ConfigureAwait(false); } @@ -73,7 +73,7 @@ public bool TryEnqueue(Block block) if (this.blocksQueueSize >= this.MaxQueueSize) { this.maxQueueSizeReached = true; - this.logger.Trace("(-)[REACHED_MAX_QUEUE_SIZE]"); + this.logger.LogTrace("(-)[REACHED_MAX_QUEUE_SIZE]"); } } else @@ -85,7 +85,7 @@ public bool TryEnqueue(Block block) if (!this.maxQueueSizeReached) { long currentBlockQueueSize = Interlocked.Add(ref this.blocksQueueSize, block.BlockSize.Value); - this.logger.Debug("Queue sized changed to {0} bytes.", currentBlockQueueSize); + this.logger.LogDebug("Queue sized changed to {0} bytes.", currentBlockQueueSize); this.blocksQueue.Enqueue(block); diff --git a/src/Stratis.Features.FederatedPeg/Wallet/FederationWalletManager.cs b/src/Stratis.Features.FederatedPeg/Wallet/FederationWalletManager.cs index 116c4a8a47..35ab18c06a 100644 --- a/src/Stratis.Features.FederatedPeg/Wallet/FederationWalletManager.cs +++ b/src/Stratis.Features.FederatedPeg/Wallet/FederationWalletManager.cs @@ -284,7 +284,7 @@ public void Start() this.asyncLoop = this.asyncProvider.CreateAndRunAsyncLoop("wallet persist job", token => { this.SaveWallet(); - this.logger.Info("Wallets saved to file at {0}.", this.dateTimeProvider.GetUtcNow()); + this.logger.LogInformation("Wallets saved to file at {0}.", this.dateTimeProvider.GetUtcNow()); return Task.CompletedTask; }, @@ -311,13 +311,13 @@ public HashHeightPair LastBlockSyncedHashHeight() { if (!this.IsWalletActive()) { - this.logger.Trace("(-)[NO_WALLET]:{0}='{1}'", nameof(this.chainIndexer.Tip), this.chainIndexer.Tip); + this.logger.LogTrace("(-)[NO_WALLET]:{0}='{1}'", nameof(this.chainIndexer.Tip), this.chainIndexer.Tip); return new HashHeightPair(this.chainIndexer.Tip); } if (this.Wallet.LastBlockSyncedHash == null && this.Wallet.LastBlockSyncedHeight == null) { - this.logger.Trace("(-)[WALLET_SYNC_BLOCK_NOT_SET]:{0}='{1}'", nameof(this.chainIndexer.Tip), this.chainIndexer.Tip); + this.logger.LogTrace("(-)[WALLET_SYNC_BLOCK_NOT_SET]:{0}='{1}'", nameof(this.chainIndexer.Tip), this.chainIndexer.Tip); return new HashHeightPair(this.chainIndexer.Tip); } @@ -346,13 +346,13 @@ public void RemoveBlocks(ChainedHeader fork) lock (this.lockObject) { - this.logger.Debug("Removing blocks back to height {0} from {1}.", fork.Height, this.LastBlockSyncedHashHeight().Height); + this.logger.LogDebug("Removing blocks back to height {0} from {1}.", fork.Height, this.LastBlockSyncedHashHeight().Height); // Remove all the UTXO that have been reorged. IEnumerable makeUnspendable = this.Wallet.MultiSigAddress.Transactions.Where(w => w.BlockHeight > fork.Height).ToList(); foreach (TransactionData transactionData in makeUnspendable) { - this.logger.Debug("Removing reorged tx '{0}'.", transactionData.Id); + this.logger.LogDebug("Removing reorged tx '{0}'.", transactionData.Id); this.Wallet.MultiSigAddress.Transactions.Remove(transactionData); if (transactionData.SpendingDetails != null) @@ -363,7 +363,7 @@ public void RemoveBlocks(ChainedHeader fork) IEnumerable makeSpendable = this.Wallet.MultiSigAddress.Transactions.Where(w => (w.SpendingDetails != null) && (w.SpendingDetails.BlockHeight > fork.Height)); foreach (TransactionData transactionData in makeSpendable) { - this.logger.Debug("Unspend transaction '{0}'.", transactionData.Id); + this.logger.LogDebug("Unspend transaction '{0}'.", transactionData.Id); transactionData.SpendingDetails = null; } @@ -403,20 +403,20 @@ public void ProcessBlock(Block block, ChainedHeader chainedHeader) if (!this.IsWalletActive(chainedHeader.Height)) { this.WalletTipHash = chainedHeader.HashBlock; - this.logger.Trace("(-)[NO_WALLET]"); + this.logger.LogTrace("(-)[NO_WALLET]"); return; } // Is this the next block. if (chainedHeader.Header.HashPrevBlock != this.WalletTipHash) { - this.logger.Debug("New block's previous hash '{0}' does not match current wallet's tip hash '{1}'.", chainedHeader.Header.HashPrevBlock, this.WalletTipHash); + this.logger.LogDebug("New block's previous hash '{0}' does not match current wallet's tip hash '{1}'.", chainedHeader.Header.HashPrevBlock, this.WalletTipHash); // The block coming in to the wallet should never be ahead of the wallet. // If the block is behind, let it pass. if (chainedHeader.Height > this.WalletTipHeight) { - this.logger.Trace("(-)[BLOCK_TOO_FAR]"); + this.logger.LogTrace("(-)[BLOCK_TOO_FAR]"); throw new WalletException("block too far in the future has arrived to the wallet"); } } @@ -449,7 +449,7 @@ public bool ProcessTransaction(Transaction transaction, int? blockHeight = null, { if (!this.IsWalletActive()) { - this.logger.Trace("(-)"); + this.logger.LogTrace("(-)"); return false; } @@ -480,14 +480,14 @@ public bool ProcessTransaction(Transaction transaction, int? blockHeight = null, List<(Transaction transaction, IWithdrawal withdrawal)> walletData = this.FindWithdrawalTransactions(withdrawal.DepositId); if ((walletData.Count == 1) && (walletData[0].withdrawal.BlockNumber != 0)) { - this.logger.Debug("Deposit '{0}' already included in block.", withdrawal.DepositId); + this.logger.LogDebug("Deposit '{0}' already included in block.", withdrawal.DepositId); return false; } // Remove this to prevent duplicates if the transaction hash has changed. if (walletData.Count != 0) { - this.logger.Debug("Removing duplicates for '{0}'.", withdrawal.DepositId); + this.logger.LogDebug("Removing duplicates for '{0}'.", withdrawal.DepositId); this.RemoveWithdrawalTransactions(withdrawal.DepositId); } } @@ -548,7 +548,7 @@ public bool CleanTransactionsPastMaxReorg(int crossChainTransferStoreTip) if (this.network.Consensus.MaxReorgLength == 0 || this.Wallet.MultiSigAddress.Transactions.Count <= MinimumRetainedTransactions) { - this.logger.Debug("Skipping clean up of federation wallet. {0}={1};{2}={3}", nameof(this.network.Consensus.MaxReorgLength), this.network.Consensus.MaxReorgLength, nameof(this.Wallet.MultiSigAddress.Transactions), this.Wallet.MultiSigAddress.Transactions.Count); + this.logger.LogDebug("Skipping clean up of federation wallet. {0}={1};{2}={3}", nameof(this.network.Consensus.MaxReorgLength), this.network.Consensus.MaxReorgLength, nameof(this.Wallet.MultiSigAddress.Transactions), this.Wallet.MultiSigAddress.Transactions.Count); return walletUpdated; } @@ -573,7 +573,7 @@ public bool CleanTransactionsPastMaxReorg(int crossChainTransferStoreTip) break; } - this.logger.Debug("Cleaned {0} transactions older than the CCTS tip less max reorg of {1}.", transactionsPastMaxReorg.Count, crossChainTransferStoreTip); + this.logger.LogDebug("Cleaned {0} transactions older than the CCTS tip less max reorg of {1}.", transactionsPastMaxReorg.Count, crossChainTransferStoreTip); return walletUpdated; } @@ -596,7 +596,7 @@ private bool RemoveTransaction(Transaction transaction) if (spentTransaction.SpendingDetails != null) { // Get the transaction being spent and unspend it. - this.logger.Debug("Unspending transaction {0}-{1}.", spentTransaction.Id, spentTransaction.Index); + this.logger.LogDebug("Unspending transaction {0}-{1}.", spentTransaction.Id, spentTransaction.Index); this.RemoveAssociatedUnconfirmedSpentByTransaction(spentTransaction.SpendingDetails.TransactionId); spentTransaction.SpendingDetails = null; updatedWallet = true; @@ -613,7 +613,7 @@ private bool RemoveTransaction(Transaction transaction) // Remove any UTXO's that were provided by this transaction from wallet. if (this.Wallet.MultiSigAddress.Transactions.TryGetTransaction(hash, index, out TransactionData foundTransaction)) { - this.logger.Debug("Removing transaction {0}-{1}.", foundTransaction.Id, foundTransaction.Index); + this.logger.LogDebug("Removing transaction {0}-{1}.", foundTransaction.Id, foundTransaction.Index); this.Wallet.MultiSigAddress.Transactions.Remove(foundTransaction); updatedWallet = true; } @@ -631,18 +631,18 @@ private void RemoveAssociatedUnconfirmedSpentByTransaction(uint256 transactionId { if (!this.Wallet.MultiSigAddress.Transactions.TryGetTransaction(transactionId, 0, out TransactionData transactionData)) { - this.logger.Debug("Spending transaction '{0}' does not exist.", transactionId); + this.logger.LogDebug("Spending transaction '{0}' does not exist.", transactionId); return; } if (transactionData.IsConfirmed()) { - this.logger.Debug("Spending transaction '{0}' was not removed as it is already confirmed.", transactionId); + this.logger.LogDebug("Spending transaction '{0}' was not removed as it is already confirmed.", transactionId); return; } this.Wallet.MultiSigAddress.Transactions.Remove(transactionData); - this.logger.Debug("'{0}' was removed.", transactionId); + this.logger.LogDebug("'{0}' was removed.", transactionId); } /// @@ -688,7 +688,7 @@ private void AddTransactionToWallet(Transaction transaction, TxOut utxo, int? bl int index = transaction.Outputs.IndexOf(utxo); if (!this.Wallet.MultiSigAddress.Transactions.TryGetTransaction(transactionHash, index, out TransactionData foundTransaction)) { - this.logger.Debug("Transaction '{0}-{1}' not found, creating. BlockHeight={2}, BlockHash={3}", transactionHash, index, blockHeight, blockHash); + this.logger.LogDebug("Transaction '{0}-{1}' not found, creating. BlockHeight={2}, BlockHash={3}", transactionHash, index, blockHeight, blockHash); TransactionData newTransaction = new TransactionData { @@ -705,7 +705,7 @@ private void AddTransactionToWallet(Transaction transaction, TxOut utxo, int? bl } else { - this.logger.Debug("Transaction '{0}-{1}' found, updating. BlockHeight={2}, BlockHash={3}.", transactionHash, index, blockHeight, blockHash); + this.logger.LogDebug("Transaction '{0}-{1}' found, updating. BlockHeight={2}, BlockHash={3}.", transactionHash, index, blockHeight, blockHash); // Update the block height and block hash. if ((foundTransaction.BlockHeight == null) && (blockHeight != null)) @@ -751,7 +751,7 @@ private void AddSpendingTransactionToWalletLocked(Transaction transaction, if (!this.Wallet.MultiSigAddress.Transactions.TryGetTransaction(spendingTransactionId, spendingTransactionIndex, out TransactionData spendingTransaction)) { // Strange, why would it be null? - this.logger.Trace("(-)[TX_NULL]"); + this.logger.LogTrace("(-)[TX_NULL]"); return; } @@ -759,19 +759,19 @@ private void AddSpendingTransactionToWalletLocked(Transaction transaction, { // If the spending tx's spending details are confirmed and this is coming in unconfirmed, ignore. // This is probably an unlucky concurrency issues, e.g. tx from mempool coming in after confirmed in a block. - this.logger.Debug("Unconfirmed spending UTXO '{0}-{1}' is being ignored as it is already confirmed in block {2}", spendingTransactionId, spendingTransactionIndex, spendingTransaction.SpendingDetails.BlockHeight); + this.logger.LogDebug("Unconfirmed spending UTXO '{0}-{1}' is being ignored as it is already confirmed in block {2}", spendingTransactionId, spendingTransactionIndex, spendingTransaction.SpendingDetails.BlockHeight); return; } // If spending details is null, always set new spending details. if (spendingTransaction.SpendingDetails == null) - this.logger.Debug("Spending UTXO '{0}-{1}' is new at height {2}, spending with tx '{3}'.", spendingTransactionId, spendingTransactionIndex, blockHeight, transaction.GetHash()); + this.logger.LogDebug("Spending UTXO '{0}-{1}' is new at height {2}, spending with tx '{3}'.", spendingTransactionId, spendingTransactionIndex, blockHeight, transaction.GetHash()); // If there are unconfirmed existing spending details, always overwrite with new one. // Could be a "more" signed tx, a FullySigned mempool tx or a confirmed block tx. if (spendingTransaction.SpendingDetails != null && spendingTransaction.SpendingDetails.BlockHeight == null) { - this.logger.Debug("Spending UTXO '{0}-{1}' has unconfirmed spending details at height {2}, spending with tx '{3}'.", spendingTransactionId, spendingTransactionIndex, blockHeight, transaction.GetHash()); + this.logger.LogDebug("Spending UTXO '{0}-{1}' has unconfirmed spending details at height {2}, spending with tx '{3}'.", spendingTransactionId, spendingTransactionIndex, blockHeight, transaction.GetHash()); //If we are overwriting existing spending details, remove the associated transaction as well. this.RemoveAssociatedUnconfirmedSpentByTransaction(spendingTransaction.SpendingDetails.TransactionId); @@ -779,7 +779,7 @@ private void AddSpendingTransactionToWalletLocked(Transaction transaction, // If the spending details are confirmed and this is also coming in confirmed, then update the spending details. if (spendingTransaction.SpendingDetails != null && spendingTransaction.SpendingDetails.BlockHeight != null && blockHeight != null) - this.logger.Debug("Spending UTXO '{0}-{1}' has confirmed spending details height {2}, spending with tx '{3}'.", spendingTransactionId, spendingTransactionIndex, blockHeight, transaction.GetHash()); + this.logger.LogDebug("Spending UTXO '{0}-{1}' has confirmed spending details height {2}, spending with tx '{3}'.", spendingTransactionId, spendingTransactionIndex, blockHeight, transaction.GetHash()); spendingTransaction.SpendingDetails = this.BuildSpendingDetails(transaction, paidToOutputs, blockHeight, blockHash, block, withdrawal); } @@ -913,7 +913,7 @@ public bool RemoveUnconfirmedTransactionData() /// public bool RemoveWithdrawalTransactions(uint256 depositId) { - this.logger.Debug("Removing transient transactions for depositId '{0}'.", depositId); + this.logger.LogDebug("Removing transient transactions for depositId '{0}'.", depositId); lock (this.lockObject) { @@ -960,7 +960,7 @@ private OutPoint EarliestOutput(Transaction transaction) if (spendingDetail.WithdrawalDetails == null) { - this.logger.Error($"Spending detail with txId '{spendingDetail.TransactionId}' has null withdrawal details, deposit id '{depositId}'"); + this.logger.LogError($"Spending detail with txId '{spendingDetail.TransactionId}' has null withdrawal details, deposit id '{depositId}'"); } var withdrawal = new Withdrawal( @@ -1058,7 +1058,7 @@ public ValidateTransactionResult ValidateTransaction(Transaction transaction, bo // Verify that the transaction has valid UTXOs. if (!this.TransactionHasValidUTXOs(transaction, coins)) { - this.logger.Error($"Transaction '{transaction.GetHash()}' does not have valid UTXOs."); + this.logger.LogError($"Transaction '{transaction.GetHash()}' does not have valid UTXOs."); return ValidateTransactionResult.Failed("Transaction does not have valid UTXOs."); } @@ -1074,7 +1074,7 @@ public ValidateTransactionResult ValidateTransaction(Transaction transaction, bo .FirstOrDefault(); if (oldestInput != null && DeterministicCoinOrdering.CompareTransactionData(earliestUnspent, oldestInput) < 0) { - this.logger.Error($"Earlier unspent UTXOs exist for tx '{transaction.GetHash()}'"); + this.logger.LogError($"Earlier unspent UTXOs exist for tx '{transaction.GetHash()}'"); return ValidateTransactionResult.Failed("Earlier unspent UTXOs exist."); } } @@ -1100,7 +1100,7 @@ public ValidateTransactionResult ValidateTransaction(Transaction transaction, bo // Trace the reason validation failed. Note that failure here doesn't mean an error necessarily. Just that the transaction is not fully signed. foreach (TransactionPolicyError transactionPolicyError in filteredErrors) { - this.logger.Debug("{0} FAILED - {1}", nameof(TransactionBuilder.Verify), transactionPolicyError.ToString()); + this.logger.LogDebug("{0} FAILED - {1}", nameof(TransactionBuilder.Verify), transactionPolicyError.ToString()); errorList.Add(transactionPolicyError.ToString()); } @@ -1135,7 +1135,7 @@ public bool ValidateConsolidatingTransaction(Transaction transaction, bool check // Trace the reason validation failed. Note that failure here doesn't mean an error necessarily. Just that the transaction is not fully signed. foreach (TransactionPolicyError transactionPolicyError in errors) { - this.logger.Info("{0} FAILED - {1}", nameof(TransactionBuilder.Verify), transactionPolicyError.ToString()); + this.logger.LogInformation("{0} FAILED - {1}", nameof(TransactionBuilder.Verify), transactionPolicyError.ToString()); } return false; @@ -1175,7 +1175,7 @@ public void UpdateLastBlockSyncedHeight(ChainedHeader chainedHeader) /// Thrown if wallet cannot be created. private FederationWallet GenerateWallet() { - this.logger.Debug("Generating the federation wallet file."); + this.logger.LogDebug("Generating the federation wallet file."); int lastBlockSyncedHeight = Math.Max(0, this.federatedPegSettings.WalletSyncFromHeight - 1); uint256 lastBlockSyncedHash = (lastBlockSyncedHeight <= this.chainIndexer.Height) ? this.chainIndexer[lastBlockSyncedHeight].HashBlock : null; @@ -1198,7 +1198,7 @@ private FederationWallet GenerateWallet() } }; - this.logger.Trace("(-)"); + this.logger.LogTrace("(-)"); return wallet; } @@ -1212,7 +1212,7 @@ public void EnableFederationWallet(string password, string mnemonic = null, stri // Protect against de-activation if the federation is already active. if (this.isFederationActive) { - this.logger.Warn("(-):[FEDERATION_ALREADY_ACTIVE]"); + this.logger.LogWarning("(-):[FEDERATION_ALREADY_ACTIVE]"); return; } @@ -1229,8 +1229,8 @@ public void EnableFederationWallet(string password, string mnemonic = null, stri } catch (NotSupportedException ex) { - this.logger.Debug("Exception occurred: {0}", ex.ToString()); - this.logger.Trace("(-)[EXCEPTION]"); + this.logger.LogDebug("Exception occurred: {0}", ex.ToString()); + this.logger.LogTrace("(-)[EXCEPTION]"); if (ex.Message == "Unknown") throw new WalletException("Please make sure you enter valid mnemonic words."); diff --git a/src/Stratis.Features.FederatedPeg/Wallet/FederationWalletSyncManager.cs b/src/Stratis.Features.FederatedPeg/Wallet/FederationWalletSyncManager.cs index 1e6a9c7c45..9ad936ef3f 100644 --- a/src/Stratis.Features.FederatedPeg/Wallet/FederationWalletSyncManager.cs +++ b/src/Stratis.Features.FederatedPeg/Wallet/FederationWalletSyncManager.cs @@ -74,7 +74,7 @@ public void Initialize() if (this.storeSettings.PruningEnabled) throw new WalletException("Wallet can not yet run on a pruned node"); - this.logger.Info("WalletSyncManager initialized. Wallet at block {0}.", this.federationWalletManager.LastBlockSyncedHashHeight().Height); + this.logger.LogInformation("WalletSyncManager initialized. Wallet at block {0}.", this.federationWalletManager.LastBlockSyncedHashHeight().Height); this.walletTip = this.chain.GetHeader(this.federationWalletManager.WalletTipHash); if (this.walletTip == null) @@ -110,7 +110,7 @@ private async Task OnProcessBlockWrapperAsync(Block block, CancellationToken can } catch (Exception e) { - this.logger.Error(e.ToString()); + this.logger.LogError(e.ToString()); } } @@ -121,7 +121,7 @@ private Task OnProcessBlockAsync(Block block, CancellationToken cancellationToke ChainedHeader newTip = this.chain.GetHeader(block.GetHash()); if (newTip == null) { - this.logger.Trace("(-)[NEW_TIP_REORG]"); + this.logger.LogTrace("(-)[NEW_TIP_REORG]"); return Task.CompletedTask; } @@ -142,12 +142,12 @@ private Task OnProcessBlockAsync(Block block, CancellationToken cancellationToke while (this.chain.GetHeader(fork.HashBlock) == null) fork = fork.Previous; - this.logger.Info("Reorg detected, going back from '{0}' to '{1}'.", this.walletTip, fork); + this.logger.LogInformation("Reorg detected, going back from '{0}' to '{1}'.", this.walletTip, fork); this.federationWalletManager.RemoveBlocks(fork); this.walletTip = fork; - this.logger.Debug("Wallet tip set to '{0}'.", this.walletTip); + this.logger.LogDebug("Wallet tip set to '{0}'.", this.walletTip); } // The new tip can be ahead or behind the wallet. @@ -158,11 +158,11 @@ private Task OnProcessBlockAsync(Block block, CancellationToken cancellationToke ChainedHeader findTip = newTip.FindAncestorOrSelf(this.walletTip); if (findTip == null) { - this.logger.Trace("(-)[NEW_TIP_AHEAD_NOT_IN_WALLET]"); + this.logger.LogTrace("(-)[NEW_TIP_AHEAD_NOT_IN_WALLET]"); return Task.CompletedTask; } - this.logger.Debug("Wallet tip '{0}' is behind the new tip '{1}'.", this.walletTip, newTip); + this.logger.LogDebug("Wallet tip '{0}' is behind the new tip '{1}'.", this.walletTip, newTip); ChainedHeader next = this.walletTip; while (next != newTip) @@ -182,7 +182,7 @@ private Task OnProcessBlockAsync(Block block, CancellationToken cancellationToke { if (cancellationToken.IsCancellationRequested) { - this.logger.Trace("(-)[CANCELLATION_REQUESTED]"); + this.logger.LogTrace("(-)[CANCELLATION_REQUESTED]"); return Task.CompletedTask; } @@ -194,13 +194,13 @@ private Task OnProcessBlockAsync(Block block, CancellationToken cancellationToke index++; if (index > 10) { - this.logger.Trace("(-)[WALLET_CATCHUP_INDEX_MAX]"); + this.logger.LogTrace("(-)[WALLET_CATCHUP_INDEX_MAX]"); return Task.CompletedTask; } // Really ugly hack to let store catch up. // This will block the entire consensus pulling. - this.logger.Warn("Wallet is behind the best chain and the next block is not found in store."); + this.logger.LogWarning("Wallet is behind the best chain and the next block is not found in store."); Thread.Sleep(100); continue; } @@ -217,14 +217,14 @@ private Task OnProcessBlockAsync(Block block, CancellationToken cancellationToke ChainedHeader findTip = this.walletTip.FindAncestorOrSelf(newTip); if (findTip == null) { - this.logger.Trace("(-)[NEW_TIP_BEHIND_NOT_IN_WALLET]"); + this.logger.LogTrace("(-)[NEW_TIP_BEHIND_NOT_IN_WALLET]"); return Task.CompletedTask; } - this.logger.Debug("Wallet tip '{0}' is ahead or equal to the new tip '{1}'.", this.walletTip, newTip); + this.logger.LogDebug("Wallet tip '{0}' is ahead or equal to the new tip '{1}'.", this.walletTip, newTip); } } - else this.logger.Debug("New block follows the previously known block '{0}'.", this.walletTip); + else this.logger.LogDebug("New block follows the previously known block '{0}'.", this.walletTip); this.walletTip = newTip; this.federationWalletManager.ProcessBlock(block, newTip); @@ -245,7 +245,7 @@ public virtual void ProcessTransaction(Transaction transaction) { Guard.NotNull(transaction, nameof(transaction)); - this.logger.Debug("Processing transaction from mempool: {0}", transaction.GetHash()); + this.logger.LogDebug("Processing transaction from mempool: {0}", transaction.GetHash()); if (this.federationWalletManager.ProcessTransaction(transaction)) this.federationWalletManager.SaveWallet(); diff --git a/src/Stratis.Features.FederatedPeg/Wallet/FederationWalletTransactionHandler.cs b/src/Stratis.Features.FederatedPeg/Wallet/FederationWalletTransactionHandler.cs index e261becc78..d172c109fa 100644 --- a/src/Stratis.Features.FederatedPeg/Wallet/FederationWalletTransactionHandler.cs +++ b/src/Stratis.Features.FederatedPeg/Wallet/FederationWalletTransactionHandler.cs @@ -104,7 +104,7 @@ public Transaction BuildTransaction(TransactionBuildContext context) if (!transactionBuilder.Verify(transaction, out TransactionPolicyError[] errors)) { string errorsMessage = string.Join(" - ", errors.Select(s => s.ToString())); - this.logger.Error($"Build transaction failed: {errorsMessage}"); + this.logger.LogError($"Build transaction failed: {errorsMessage}"); throw new WalletException($"Could not build the transaction. Details: {errorsMessage}"); } }