|
| 1 | +import functools |
| 2 | +import logging |
| 3 | +from typing import Literal |
| 4 | + |
1 | 5 | from zarr._version import version as __version__ |
2 | 6 | from zarr.api.synchronous import ( |
3 | 7 | array, |
|
37 | 41 | # in case setuptools scm screw up and find version to be 0.0.0 |
38 | 42 | assert not __version__.startswith("0.0.0") |
39 | 43 |
|
| 44 | +_logger = logging.getLogger(__name__) |
| 45 | + |
40 | 46 |
|
41 | 47 | def print_debug_info() -> None: |
42 | 48 | """ |
@@ -85,6 +91,58 @@ def print_packages(packages: list[str]) -> None: |
85 | 91 | print_packages(optional) |
86 | 92 |
|
87 | 93 |
|
| 94 | +# The decorator ensures this always returns the same handler (and it is only |
| 95 | +# attached once). |
| 96 | +@functools.cache |
| 97 | +def _ensure_handler() -> logging.Handler: |
| 98 | + """ |
| 99 | + The first time this function is called, attach a `StreamHandler` using the |
| 100 | + same format as `logging.basicConfig` to the Zarr-Python root logger. |
| 101 | +
|
| 102 | + Return this handler every time this function is called. |
| 103 | + """ |
| 104 | + handler = logging.StreamHandler() |
| 105 | + handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT)) |
| 106 | + _logger.addHandler(handler) |
| 107 | + return handler |
| 108 | + |
| 109 | + |
| 110 | +def set_log_level( |
| 111 | + level: Literal["NOTSET", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], |
| 112 | +) -> None: |
| 113 | + """Set the logging level for Zarr-Python. |
| 114 | +
|
| 115 | + Zarr-Python uses the standard library `logging` framework under the root |
| 116 | + logger 'zarr'. This is a helper function to: |
| 117 | +
|
| 118 | + - set Zarr-Python's root logger level |
| 119 | + - set the root logger handler's level, creating the handler |
| 120 | + if it does not exist yet |
| 121 | +
|
| 122 | + Parameters |
| 123 | + ---------- |
| 124 | + level : str |
| 125 | + The logging level to set. |
| 126 | + """ |
| 127 | + _logger.setLevel(level) |
| 128 | + _ensure_handler().setLevel(level) |
| 129 | + |
| 130 | + |
| 131 | +def set_format(log_format: str) -> None: |
| 132 | + """Set the format of logging messages from Zarr-Python. |
| 133 | +
|
| 134 | + Zarr-Python uses the standard library `logging` framework under the root |
| 135 | + logger 'zarr'. This sets the format of log messages from the root logger's StreamHandler. |
| 136 | +
|
| 137 | + Parameters |
| 138 | + ---------- |
| 139 | + log_format : str |
| 140 | + A string determining the log format (as defined in the standard library's `logging` module |
| 141 | + for logging.Formatter) |
| 142 | + """ |
| 143 | + _ensure_handler().setFormatter(logging.Formatter(fmt=log_format)) |
| 144 | + |
| 145 | + |
88 | 146 | __all__ = [ |
89 | 147 | "Array", |
90 | 148 | "AsyncArray", |
|
0 commit comments