Created
June 14, 2018 20:58
-
-
Save LiraNuna/50270d50e9cc38bd1bfcac0371d1df5a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
class MyLogger: | |
enabled = True | |
def log(self, something: str) -> None: | |
if not self.enabled: | |
print("NOT LOGGING:", something) | |
return | |
print(something) | |
class SilenceLogs: | |
def __enter__(self): | |
MyLogger.enabled = False | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
MyLogger.enabled = True | |
class AsyncSilenceLogs: | |
async def __aenter__(self): | |
MyLogger.enabled = False | |
async def __aexit__(self, exc_type, exc_val, exc_tb): | |
MyLogger.enabled = True | |
async def log_after_1_sec(something: str) -> None: | |
await asyncio.sleep(1) | |
MyLogger().log(f'{something} after 1 second') | |
async def suppressed_logging_after_2_sec(something: str) -> None: | |
await asyncio.sleep(1) | |
with SilenceLogs(): | |
await log_after_1_sec(something) | |
async def async_suppressed_logging_after_2_sec(something: str) -> None: | |
await asyncio.sleep(1) | |
async with AsyncSilenceLogs(): | |
await log_after_1_sec(something) | |
async def main() -> None: | |
print("should -> should not") | |
await asyncio.gather( | |
log_after_1_sec("Should be logged"), | |
suppressed_logging_after_2_sec("Should not be logged"), | |
) | |
print("should not -> should") | |
await asyncio.gather( | |
suppressed_logging_after_2_sec("Should not be logged"), | |
log_after_1_sec("Should be logged"), | |
) | |
print("[async] should -> should not") | |
await asyncio.gather( | |
log_after_1_sec("Should be logged"), | |
async_suppressed_logging_after_2_sec("Should not be logged"), | |
) | |
print("[async] should not -> should") | |
await asyncio.gather( | |
async_suppressed_logging_after_2_sec("Should not be logged"), | |
log_after_1_sec("Should be logged"), | |
) | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(main()) | |
loop.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment