Skip to content

Commit

Permalink
feat: improve means to disable logging in ape (#2493)
Browse files Browse the repository at this point in the history
  • Loading branch information
antazoey authored Feb 6, 2025
1 parent 142d51b commit c098982
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 1 deletion.
32 changes: 32 additions & 0 deletions docs/userguides/logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,15 @@ ape my_cmd -v ERROR

*NOTE*: You can put the verbosity flag anywhere in your CLI command for _most_ commands.

To disable logging completely, you can use keyword "DISABLE" or "NONE" as the `--verbosity` value:

```shell
ape my_cmd -v NONE
```

Now, Ape won't log at all.
**This can be useful if you need the output of the CLI for something else.**

## Python Logging

You can also import and use the logger in your own Python scripts or commands:
Expand All @@ -49,3 +58,26 @@ def main():
logger.info("You have entered `main()`.")
logger.set_level(LogLevel.WARNING)
```

You can also use the `.at_level()` context-manager to temporarily change the log-level:

```python
from ape.logging import logger, LogLevel

def main():
with logger.at_level(LogLevel.WARNING):
# An operation where you want to ensure WARN-level logs appear.
pass
```

You can also disable the logger in Python:

```python
from ape.logging import logger, LogLevel

def main():
logger.disable() # Turns off logging entirely.
with logger.disabled():
# Turns off logging in a context - useful for capturing stdout.
pass
```
2 changes: 2 additions & 0 deletions src/ape/cli/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ def set_level(ctx, param, value):
value = value.upper()
if value.startswith("LOGLEVEL."):
value = value.split(".")[-1].strip()
elif value in ("DISABLE", "NONE"):
value = ape_logger.DISABLE_LEVEL

if callback is not None:
value = callback(ctx, param, value)
Expand Down
10 changes: 9 additions & 1 deletion src/ape/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ def emit(self, record):
class ApeLogger:
_mentioned_verbosity_option = False
_extra_loggers: dict[str, logging.Logger] = {}
DISABLE_LEVEL: int = 100_000

def __init__(
self,
Expand Down Expand Up @@ -216,12 +217,19 @@ def at_level(self, level: Union[str, int, LogLevel]) -> Iterator:
Returns:
Iterator
"""

initial_level = self.level
self.set_level(level)
yield
self.set_level(initial_level)

def disable(self):
self.set_level(self.DISABLE_LEVEL)

@contextmanager
def disabled(self):
with self.at_level(self.DISABLE_LEVEL):
yield

def log_error(self, err: Exception):
"""
Avoids logging empty messages.
Expand Down
11 changes: 11 additions & 0 deletions tests/functional/test_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,14 @@ def test_sanitize_url(url):
actual = sanitize_url(url)
expected = "https://example.com/[hidden]"
assert actual == expected


def test_disabled(ape_caplog):
message = "Can you hear me now?"
with logger.disabled():
logger.error(message)
assert message not in ape_caplog.head

# Show it is back.
logger.error(message)
assert message in ape_caplog.head

0 comments on commit c098982

Please sign in to comment.