refactored code to ensure logging comes in proper order