acodo 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- acodo-0.3.0/LICENSE +21 -0
- acodo-0.3.0/PKG-INFO +94 -0
- acodo-0.3.0/README.md +76 -0
- acodo-0.3.0/pyproject.toml +121 -0
- acodo-0.3.0/pyproject.toml.orig +103 -0
- acodo-0.3.0/src/acodo/__init__.py +11 -0
- acodo-0.3.0/src/acodo/logger/__init__.py +13 -0
- acodo-0.3.0/src/acodo/logger/logger.py +249 -0
- acodo-0.3.0/src/acodo/py.typed +0 -0
- acodo-0.3.0/src/acodo/utils/__init__.py +263 -0
- acodo-0.3.0/src/acodo/utils/checkers.py +80 -0
- acodo-0.3.0/src/acodo/utils/converters.py +569 -0
- acodo-0.3.0/src/acodo/utils/getters.py +478 -0
- acodo-0.3.0/src/acodo/utils/parsers.py +270 -0
- acodo-0.3.0/src/acodo/utils/types.py +107 -0
- acodo-0.3.0/src/acodo/utils/validators.py +787 -0
acodo-0.3.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 isidro-rodriguez
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
acodo-0.3.0/PKG-INFO
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: acodo
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Utilidades puras del framework Acodo: validación, conversión, parseo y logger.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
12
|
+
Classifier: Typing :: Typed
|
|
13
|
+
Requires-Python: >=3.13
|
|
14
|
+
Project-URL: Changelog, https://github.com/isidro-rodriguez/acodo/blob/main/CHANGELOG.md
|
|
15
|
+
Project-URL: Documentation, https://isidro-rodriguez.github.io/acodo/
|
|
16
|
+
Project-URL: Repository, https://github.com/isidro-rodriguez/acodo
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# acodo
|
|
20
|
+
|
|
21
|
+
Biblioteca de utilidades de Acodo para **Python >= 3.13**. No tiene
|
|
22
|
+
dependencias externas: solo usa la biblioteca estándar.
|
|
23
|
+
|
|
24
|
+
> Antes se publicaba como `acodo-framework`; ese nombre queda obsoleto.
|
|
25
|
+
|
|
26
|
+
## 🚀 Instalación
|
|
27
|
+
|
|
28
|
+
Desde [PyPI](https://pypi.org/project/acodo/):
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
uv add acodo
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## 🛠️ Uso
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from acodo.logger import Logger
|
|
38
|
+
from acodo.utils import to_bool, valid_email
|
|
39
|
+
|
|
40
|
+
to_bool("sí") # True
|
|
41
|
+
valid_email("hola") # False
|
|
42
|
+
|
|
43
|
+
log = Logger("miapp")
|
|
44
|
+
log.info("Procesando %(n)s ficheros", n=3)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## 📦 Módulos
|
|
48
|
+
|
|
49
|
+
- `acodo.utils`: funciones agrupadas por prefijo (`get_*`, `has_*`, `parse_*`,
|
|
50
|
+
`to_*`, `valid_*`) y el tipo `SocialLink`. Convenciones y errores en el docstring
|
|
51
|
+
del paquete.
|
|
52
|
+
- `acodo.logger`: `Logger`; consola y/o fichero con rotación diaria.
|
|
53
|
+
|
|
54
|
+
`acodo.logger` depende de `acodo.utils`, nunca al revés.
|
|
55
|
+
|
|
56
|
+
## 📁 Estructura
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
src/acodo/
|
|
60
|
+
├── utils/
|
|
61
|
+
│ ├── checkers.py # has_*
|
|
62
|
+
│ ├── converters.py # to_*
|
|
63
|
+
│ ├── getters.py # get_*
|
|
64
|
+
│ ├── parsers.py # parse_*
|
|
65
|
+
│ ├── types.py # SocialLink
|
|
66
|
+
│ └── validators.py # valid_*
|
|
67
|
+
└── logger/
|
|
68
|
+
└── logger.py # Logger
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## 🧪 Desarrollo
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
uv sync
|
|
75
|
+
uv run ruff format .
|
|
76
|
+
uv run ruff check .
|
|
77
|
+
uv run ty check
|
|
78
|
+
uv run pytest
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Los hooks de `pre-commit` cubren formato, lint, tipos y tests; la etapa `pre-push` añade
|
|
82
|
+
cobertura y la construcción de la documentación, que vive en `docs/` y se genera con
|
|
83
|
+
[Zensical](https://zensical.org) (`uv run zensical serve` / `uv run zensical build`).
|
|
84
|
+
|
|
85
|
+
## Enlaces
|
|
86
|
+
|
|
87
|
+
- Repositorio: <https://github.com/isidro-rodriguez/acodo>
|
|
88
|
+
- Documentación: <https://isidro-rodriguez.github.io/acodo/>
|
|
89
|
+
- PyPI: <https://pypi.org/project/acodo/>
|
|
90
|
+
- Plantilla de proyecto: <https://github.com/isidro-rodriguez/acodo-template>
|
|
91
|
+
|
|
92
|
+
## Licencia
|
|
93
|
+
|
|
94
|
+
[MIT](https://github.com/isidro-rodriguez/acodo/blob/main/LICENSE).
|
acodo-0.3.0/README.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# acodo
|
|
2
|
+
|
|
3
|
+
Biblioteca de utilidades de Acodo para **Python >= 3.13**. No tiene
|
|
4
|
+
dependencias externas: solo usa la biblioteca estándar.
|
|
5
|
+
|
|
6
|
+
> Antes se publicaba como `acodo-framework`; ese nombre queda obsoleto.
|
|
7
|
+
|
|
8
|
+
## 🚀 Instalación
|
|
9
|
+
|
|
10
|
+
Desde [PyPI](https://pypi.org/project/acodo/):
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
uv add acodo
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## 🛠️ Uso
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
from acodo.logger import Logger
|
|
20
|
+
from acodo.utils import to_bool, valid_email
|
|
21
|
+
|
|
22
|
+
to_bool("sí") # True
|
|
23
|
+
valid_email("hola") # False
|
|
24
|
+
|
|
25
|
+
log = Logger("miapp")
|
|
26
|
+
log.info("Procesando %(n)s ficheros", n=3)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## 📦 Módulos
|
|
30
|
+
|
|
31
|
+
- `acodo.utils`: funciones agrupadas por prefijo (`get_*`, `has_*`, `parse_*`,
|
|
32
|
+
`to_*`, `valid_*`) y el tipo `SocialLink`. Convenciones y errores en el docstring
|
|
33
|
+
del paquete.
|
|
34
|
+
- `acodo.logger`: `Logger`; consola y/o fichero con rotación diaria.
|
|
35
|
+
|
|
36
|
+
`acodo.logger` depende de `acodo.utils`, nunca al revés.
|
|
37
|
+
|
|
38
|
+
## 📁 Estructura
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
src/acodo/
|
|
42
|
+
├── utils/
|
|
43
|
+
│ ├── checkers.py # has_*
|
|
44
|
+
│ ├── converters.py # to_*
|
|
45
|
+
│ ├── getters.py # get_*
|
|
46
|
+
│ ├── parsers.py # parse_*
|
|
47
|
+
│ ├── types.py # SocialLink
|
|
48
|
+
│ └── validators.py # valid_*
|
|
49
|
+
└── logger/
|
|
50
|
+
└── logger.py # Logger
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## 🧪 Desarrollo
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
uv sync
|
|
57
|
+
uv run ruff format .
|
|
58
|
+
uv run ruff check .
|
|
59
|
+
uv run ty check
|
|
60
|
+
uv run pytest
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Los hooks de `pre-commit` cubren formato, lint, tipos y tests; la etapa `pre-push` añade
|
|
64
|
+
cobertura y la construcción de la documentación, que vive en `docs/` y se genera con
|
|
65
|
+
[Zensical](https://zensical.org) (`uv run zensical serve` / `uv run zensical build`).
|
|
66
|
+
|
|
67
|
+
## Enlaces
|
|
68
|
+
|
|
69
|
+
- Repositorio: <https://github.com/isidro-rodriguez/acodo>
|
|
70
|
+
- Documentación: <https://isidro-rodriguez.github.io/acodo/>
|
|
71
|
+
- PyPI: <https://pypi.org/project/acodo/>
|
|
72
|
+
- Plantilla de proyecto: <https://github.com/isidro-rodriguez/acodo-template>
|
|
73
|
+
|
|
74
|
+
## Licencia
|
|
75
|
+
|
|
76
|
+
[MIT](https://github.com/isidro-rodriguez/acodo/blob/main/LICENSE).
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "acodo"
|
|
3
|
+
version = "0.3.0"
|
|
4
|
+
description = "Utilidades puras del framework Acodo: validación, conversión, parseo y logger."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.13"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Development Status :: 3 - Alpha",
|
|
11
|
+
"Intended Audience :: Developers",
|
|
12
|
+
"Programming Language :: Python :: 3",
|
|
13
|
+
"Programming Language :: Python :: 3.13",
|
|
14
|
+
"Programming Language :: Python :: 3.14",
|
|
15
|
+
"Typing :: Typed",
|
|
16
|
+
]
|
|
17
|
+
dependencies = []
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Changelog = "https://github.com/isidro-rodriguez/acodo/blob/main/CHANGELOG.md"
|
|
21
|
+
Documentation = "https://isidro-rodriguez.github.io/acodo/"
|
|
22
|
+
Repository = "https://github.com/isidro-rodriguez/acodo"
|
|
23
|
+
|
|
24
|
+
[dependency-groups]
|
|
25
|
+
dev = [
|
|
26
|
+
"mkdocstrings-python>=2.0.9",
|
|
27
|
+
"pre-commit>=4.7.0",
|
|
28
|
+
"pytest>=9.1.1",
|
|
29
|
+
"pytest-cov>=7.1.0",
|
|
30
|
+
"ruff>=0.17.1",
|
|
31
|
+
"ty>=0.0.89",
|
|
32
|
+
"zensical>=0.0.71",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["uv_build>=0.11.7,<0.12.0"]
|
|
37
|
+
build-backend = "uv_build"
|
|
38
|
+
|
|
39
|
+
[tool.coverage.run]
|
|
40
|
+
source = ["src"]
|
|
41
|
+
branch = true
|
|
42
|
+
omit = [
|
|
43
|
+
"*/tests/*",
|
|
44
|
+
"*/__init__.py",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
[tool.coverage.report]
|
|
48
|
+
exclude_also = [
|
|
49
|
+
"pragma: no cover",
|
|
50
|
+
"if TYPE_CHECKING:",
|
|
51
|
+
"if __name__ == .__main__.:",
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
[tool.pytest.ini_options]
|
|
55
|
+
addopts = [
|
|
56
|
+
"-ra",
|
|
57
|
+
"--strict-markers",
|
|
58
|
+
"--import-mode=importlib",
|
|
59
|
+
"--doctest-modules",
|
|
60
|
+
]
|
|
61
|
+
markers = [
|
|
62
|
+
"""slow: marks tests as slow (deselect with '-m "not slow"')""",
|
|
63
|
+
"integration: marks tests as integration tests",
|
|
64
|
+
]
|
|
65
|
+
python_classes = ["Test*"]
|
|
66
|
+
python_files = ["test_*.py"]
|
|
67
|
+
python_functions = ["test_*"]
|
|
68
|
+
testpaths = [
|
|
69
|
+
"src",
|
|
70
|
+
"tests",
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
[tool.ruff]
|
|
74
|
+
line-length = 88
|
|
75
|
+
target-version = "py313"
|
|
76
|
+
|
|
77
|
+
[tool.ruff.lint]
|
|
78
|
+
select = [
|
|
79
|
+
"E",
|
|
80
|
+
"F",
|
|
81
|
+
"W",
|
|
82
|
+
"I",
|
|
83
|
+
"N",
|
|
84
|
+
"UP",
|
|
85
|
+
"B",
|
|
86
|
+
"SIM",
|
|
87
|
+
"C4",
|
|
88
|
+
"PERF",
|
|
89
|
+
"PTH",
|
|
90
|
+
"RUF",
|
|
91
|
+
"D",
|
|
92
|
+
]
|
|
93
|
+
|
|
94
|
+
[tool.ruff.lint.pydocstyle]
|
|
95
|
+
convention = "google"
|
|
96
|
+
|
|
97
|
+
[tool.ruff.lint.isort]
|
|
98
|
+
known-first-party = ["acodo"]
|
|
99
|
+
|
|
100
|
+
[tool.ruff.lint.per-file-ignores]
|
|
101
|
+
"tests/**" = ["D"]
|
|
102
|
+
|
|
103
|
+
[tool.ty.environment]
|
|
104
|
+
python-version = "3.13"
|
|
105
|
+
|
|
106
|
+
[tool.ty.src]
|
|
107
|
+
include = [
|
|
108
|
+
"src",
|
|
109
|
+
"tests",
|
|
110
|
+
]
|
|
111
|
+
|
|
112
|
+
[tool.ty.analysis]
|
|
113
|
+
strict-equality-semantics = true
|
|
114
|
+
strict-generic-narrowing = true
|
|
115
|
+
|
|
116
|
+
[tool.ty.rules]
|
|
117
|
+
possibly-unresolved-reference = "error"
|
|
118
|
+
unused-ignore-comment = "warn"
|
|
119
|
+
|
|
120
|
+
[tool.uv.build-backend]
|
|
121
|
+
module-name = "acodo"
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# pyproject.toml
|
|
2
|
+
[project]
|
|
3
|
+
name = "acodo"
|
|
4
|
+
version = "0.3.0"
|
|
5
|
+
description = "Utilidades puras del framework Acodo: validación, conversión, parseo y logger."
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
requires-python = ">=3.13"
|
|
8
|
+
license = "MIT"
|
|
9
|
+
license-files = ["LICENSE"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Development Status :: 3 - Alpha",
|
|
12
|
+
"Intended Audience :: Developers",
|
|
13
|
+
"Programming Language :: Python :: 3",
|
|
14
|
+
"Programming Language :: Python :: 3.13",
|
|
15
|
+
"Programming Language :: Python :: 3.14",
|
|
16
|
+
"Typing :: Typed",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
# Sin dependencias en tiempo de ejecución: solo biblioteca estándar.
|
|
20
|
+
dependencies = []
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Changelog = "https://github.com/isidro-rodriguez/acodo/blob/main/CHANGELOG.md"
|
|
24
|
+
Documentation = "https://isidro-rodriguez.github.io/acodo/"
|
|
25
|
+
Repository = "https://github.com/isidro-rodriguez/acodo"
|
|
26
|
+
|
|
27
|
+
[dependency-groups]
|
|
28
|
+
dev = [
|
|
29
|
+
"mkdocstrings-python>=2.0.9",
|
|
30
|
+
"pre-commit>=4.7.0",
|
|
31
|
+
"pytest>=9.1.1",
|
|
32
|
+
"pytest-cov>=7.1.0",
|
|
33
|
+
"ruff>=0.17.1",
|
|
34
|
+
"ty>=0.0.89",
|
|
35
|
+
"zensical>=0.0.71",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[build-system]
|
|
39
|
+
requires = ["uv_build>=0.11.7,<0.12.0"]
|
|
40
|
+
build-backend = "uv_build"
|
|
41
|
+
|
|
42
|
+
# --- Cobertura (pytest-cov) --------------------------------------------------
|
|
43
|
+
[tool.coverage.run]
|
|
44
|
+
source = ["src"]
|
|
45
|
+
branch = true
|
|
46
|
+
omit = [
|
|
47
|
+
"*/tests/*",
|
|
48
|
+
"*/__init__.py",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
[tool.coverage.report]
|
|
52
|
+
exclude_also = [
|
|
53
|
+
"pragma: no cover",
|
|
54
|
+
"if TYPE_CHECKING:",
|
|
55
|
+
"if __name__ == .__main__.:",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
# --- pytest ------------------------------------------------------------------
|
|
59
|
+
[tool.pytest.ini_options]
|
|
60
|
+
addopts = ["-ra", "--strict-markers", "--import-mode=importlib", "--doctest-modules"]
|
|
61
|
+
markers = [
|
|
62
|
+
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
|
|
63
|
+
"integration: marks tests as integration tests",
|
|
64
|
+
]
|
|
65
|
+
python_classes = ["Test*"]
|
|
66
|
+
python_files = ["test_*.py"]
|
|
67
|
+
python_functions = ["test_*"]
|
|
68
|
+
testpaths = ["src", "tests"]
|
|
69
|
+
|
|
70
|
+
# --- Ruff: formato y linting -------------------------------------------------
|
|
71
|
+
[tool.ruff]
|
|
72
|
+
line-length = 88
|
|
73
|
+
target-version = "py313"
|
|
74
|
+
|
|
75
|
+
[tool.ruff.lint]
|
|
76
|
+
select = ["E", "F", "W", "I", "N", "UP", "B", "SIM", "C4", "PERF", "PTH", "RUF", "D"]
|
|
77
|
+
|
|
78
|
+
[tool.ruff.lint.pydocstyle]
|
|
79
|
+
convention = "google"
|
|
80
|
+
|
|
81
|
+
[tool.ruff.lint.isort]
|
|
82
|
+
known-first-party = ["acodo"]
|
|
83
|
+
|
|
84
|
+
[tool.ruff.lint.per-file-ignores]
|
|
85
|
+
"tests/**" = ["D"]
|
|
86
|
+
|
|
87
|
+
# --- ty: comprobación de tipos de Astral -------------------------------------
|
|
88
|
+
[tool.ty.environment]
|
|
89
|
+
python-version = "3.13"
|
|
90
|
+
|
|
91
|
+
[tool.ty.src]
|
|
92
|
+
include = ["src", "tests"]
|
|
93
|
+
|
|
94
|
+
[tool.ty.analysis]
|
|
95
|
+
strict-equality-semantics = true
|
|
96
|
+
strict-generic-narrowing = true
|
|
97
|
+
|
|
98
|
+
[tool.ty.rules]
|
|
99
|
+
possibly-unresolved-reference = "error"
|
|
100
|
+
unused-ignore-comment = "warn"
|
|
101
|
+
|
|
102
|
+
[tool.uv.build-backend]
|
|
103
|
+
module-name = "acodo"
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Acodo Framework: utilidades puras en Python, sin dependencias externas.
|
|
2
|
+
|
|
3
|
+
Subpaquetes:
|
|
4
|
+
|
|
5
|
+
- `acodo.utils`: validación, conversión, parseo, formateo y obtención de valores.
|
|
6
|
+
- `acodo.logger`: logger con destino configurable (consola y/o fichero).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from importlib.metadata import version
|
|
10
|
+
|
|
11
|
+
__version__ = version("acodo")
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Logger de Acodo: salida configurable a consola y fichero con rotación diaria.
|
|
2
|
+
|
|
3
|
+
Uso:
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from acodo.logger import Logger
|
|
7
|
+
|
|
8
|
+
log = Logger("miapp")
|
|
9
|
+
log.info("Procesando %(n)s ficheros", n=3)
|
|
10
|
+
```
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from .logger import Logger as Logger
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""Logger con destino configurable (consola y/o fichero) sobre ``logging``.
|
|
2
|
+
|
|
3
|
+
Ofrece `Logger`, un wrapper que permite decidir en cada mensaje si se muestra
|
|
4
|
+
por consola, se escribe en el fichero de log o ambos. Se configura una sola vez
|
|
5
|
+
por nombre y no toca el logger raíz.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import pprint
|
|
13
|
+
import sys
|
|
14
|
+
from logging.handlers import TimedRotatingFileHandler
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
from acodo.utils.validators import valid_filename
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from collections.abc import Mapping
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
_RESET = "\u001b[0m"
|
|
25
|
+
|
|
26
|
+
_LEVEL_COLORS = {
|
|
27
|
+
logging.DEBUG: "\u001b[30;1m",
|
|
28
|
+
logging.INFO: "\u001b[34;1m",
|
|
29
|
+
logging.WARNING: "\u001b[33;1m",
|
|
30
|
+
logging.ERROR: "\u001b[31;1m",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _prettify(value: Any) -> str:
|
|
35
|
+
"""Convierte un valor en una representación legible de varias líneas.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
value: Valor a formatear.
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
Cadena formateada con ``pprint`` para contenedores o ``str`` para el
|
|
42
|
+
resto.
|
|
43
|
+
"""
|
|
44
|
+
if isinstance(value, (dict, list, tuple, set)):
|
|
45
|
+
return pprint.pformat(value, indent=4, width=120)
|
|
46
|
+
return str(value)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _DestinationFilter(logging.Filter):
|
|
50
|
+
"""Filtra registros según el destino solicitado (consola o fichero)."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, key: str) -> None:
|
|
53
|
+
super().__init__()
|
|
54
|
+
self._key = key
|
|
55
|
+
|
|
56
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
57
|
+
# Un registro sin la marca (emitido directamente con `logging`) se
|
|
58
|
+
# deja pasar a todos los destinos.
|
|
59
|
+
return bool(getattr(record, self._key, True))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class _ConsoleFormatter(logging.Formatter):
|
|
63
|
+
"""Antepone `[NIVEL]` al mensaje, con color solo si la salida es un terminal."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, *, color: bool) -> None:
|
|
66
|
+
super().__init__("%(message)s")
|
|
67
|
+
self._color = color
|
|
68
|
+
|
|
69
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
70
|
+
tag = f"[{record.levelname}]"
|
|
71
|
+
if self._color and record.levelno in _LEVEL_COLORS:
|
|
72
|
+
tag = f"{_LEVEL_COLORS[record.levelno]}{tag}{_RESET}"
|
|
73
|
+
return f"{tag} {super().format(record)}"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Logger:
|
|
77
|
+
"""Wrapper sobre ``logging`` que permite elegir el destino de cada mensaje.
|
|
78
|
+
|
|
79
|
+
Los valores con nombre se interpolan con ``%(nombre)s``; un ``%`` literal en
|
|
80
|
+
``msg`` debe escribirse ``%%`` cuando se pasan valores.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(
|
|
84
|
+
self,
|
|
85
|
+
name: str,
|
|
86
|
+
*,
|
|
87
|
+
file: Path | None = None,
|
|
88
|
+
debug: bool = False,
|
|
89
|
+
) -> None:
|
|
90
|
+
"""Crea el logger `name`, o reutiliza el ya configurado con ese nombre.
|
|
91
|
+
|
|
92
|
+
La configuración es idempotente por nombre: solo se realiza la primera vez.
|
|
93
|
+
En llamadas posteriores con el mismo nombre se reutiliza el logger ya
|
|
94
|
+
configurado y se ignoran `debug` y `file`. No se modifica el logger raíz.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
name: Nombre del logger.
|
|
98
|
+
file: Ruta del fichero de log, con rotación diaria y 7 copias. Si es
|
|
99
|
+
`None`, solo se escribe por consola. Se crean los directorios que
|
|
100
|
+
falten.
|
|
101
|
+
debug: Si `True`, activa el nivel `DEBUG` (por defecto, `INFO`).
|
|
102
|
+
|
|
103
|
+
Raises:
|
|
104
|
+
ValueError: Si `name` está vacío o `file` no tiene un nombre de
|
|
105
|
+
fichero válido.
|
|
106
|
+
|
|
107
|
+
Examples:
|
|
108
|
+
>>> log = Logger("ejemplo")
|
|
109
|
+
>>> log.info("Procesando %(n)s ficheros", n=3)
|
|
110
|
+
[INFO] Procesando 3 ficheros
|
|
111
|
+
"""
|
|
112
|
+
if not name.strip():
|
|
113
|
+
raise ValueError("El nombre del logger no puede estar vacío.")
|
|
114
|
+
if file is not None and not valid_filename(file.name):
|
|
115
|
+
raise ValueError(f"Nombre de fichero de log no válido: {file.name!r}.")
|
|
116
|
+
|
|
117
|
+
self._logger = logging.getLogger(name)
|
|
118
|
+
if not self._logger.handlers:
|
|
119
|
+
self._configure(file=file, debug=debug)
|
|
120
|
+
|
|
121
|
+
def error(
|
|
122
|
+
self,
|
|
123
|
+
msg: str,
|
|
124
|
+
exc_info: bool = False,
|
|
125
|
+
console: bool = True,
|
|
126
|
+
file: bool = True,
|
|
127
|
+
**kwargs: object,
|
|
128
|
+
) -> None:
|
|
129
|
+
"""Registra un mensaje de nivel error.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
msg: Mensaje a registrar.
|
|
133
|
+
exc_info: Si `True`, añade la traza de la excepción activa.
|
|
134
|
+
console: Si `True`, se muestra por consola.
|
|
135
|
+
file: Si `True`, se escribe en el fichero de log.
|
|
136
|
+
**kwargs: Valores para interpolar en `msg` con `%(nombre)s`.
|
|
137
|
+
"""
|
|
138
|
+
self._log(logging.ERROR, msg, console, file, kwargs, exc_info=exc_info)
|
|
139
|
+
|
|
140
|
+
def warning(
|
|
141
|
+
self,
|
|
142
|
+
msg: str,
|
|
143
|
+
console: bool = True,
|
|
144
|
+
file: bool = True,
|
|
145
|
+
**kwargs: object,
|
|
146
|
+
) -> None:
|
|
147
|
+
"""Registra un mensaje de nivel aviso.
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
msg: Mensaje a registrar.
|
|
151
|
+
console: Si `True`, se muestra por consola.
|
|
152
|
+
file: Si `True`, se escribe en el fichero de log.
|
|
153
|
+
**kwargs: Valores para interpolar en `msg` con `%(nombre)s`.
|
|
154
|
+
"""
|
|
155
|
+
self._log(logging.WARNING, msg, console, file, kwargs)
|
|
156
|
+
|
|
157
|
+
def info(
|
|
158
|
+
self,
|
|
159
|
+
msg: str,
|
|
160
|
+
console: bool = True,
|
|
161
|
+
file: bool = True,
|
|
162
|
+
**kwargs: object,
|
|
163
|
+
) -> None:
|
|
164
|
+
"""Registra un mensaje de nivel información.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
msg: Mensaje a registrar.
|
|
168
|
+
console: Si `True`, se muestra por consola.
|
|
169
|
+
file: Si `True`, se escribe en el fichero de log.
|
|
170
|
+
**kwargs: Valores para interpolar en `msg` con `%(nombre)s`.
|
|
171
|
+
"""
|
|
172
|
+
self._log(logging.INFO, msg, console, file, kwargs)
|
|
173
|
+
|
|
174
|
+
def debug(
|
|
175
|
+
self,
|
|
176
|
+
msg: str,
|
|
177
|
+
console: bool = True,
|
|
178
|
+
file: bool = True,
|
|
179
|
+
**kwargs: object,
|
|
180
|
+
) -> None:
|
|
181
|
+
"""Registra un mensaje de nivel depuración.
|
|
182
|
+
|
|
183
|
+
Los contenedores (`dict`, `list`, `tuple`, `set`) pasados como valores
|
|
184
|
+
se formatean en varias líneas para facilitar su lectura.
|
|
185
|
+
|
|
186
|
+
Args:
|
|
187
|
+
msg: Mensaje a registrar.
|
|
188
|
+
console: Si `True`, se muestra por consola.
|
|
189
|
+
file: Si `True`, se escribe en el fichero de log.
|
|
190
|
+
**kwargs: Valores para interpolar en `msg` con `%(nombre)s`.
|
|
191
|
+
"""
|
|
192
|
+
values = {name: _prettify(value) for name, value in kwargs.items()}
|
|
193
|
+
self._log(logging.DEBUG, msg, console, file, values)
|
|
194
|
+
|
|
195
|
+
def _configure(self, *, file: Path | None, debug: bool) -> None:
|
|
196
|
+
# Nivel, handler de consola y, si se pide, handler de fichero rotativo.
|
|
197
|
+
self._logger.setLevel(logging.DEBUG if debug else logging.INFO)
|
|
198
|
+
self._logger.propagate = False
|
|
199
|
+
|
|
200
|
+
color = sys.stdout.isatty() and "NO_COLOR" not in os.environ
|
|
201
|
+
console_handler = logging.StreamHandler(sys.stdout)
|
|
202
|
+
console_handler.setFormatter(_ConsoleFormatter(color=color))
|
|
203
|
+
console_handler.addFilter(_DestinationFilter("to_console"))
|
|
204
|
+
self._logger.addHandler(console_handler)
|
|
205
|
+
|
|
206
|
+
if file is not None:
|
|
207
|
+
file.parent.mkdir(parents=True, exist_ok=True)
|
|
208
|
+
file_handler = TimedRotatingFileHandler(
|
|
209
|
+
filename=file,
|
|
210
|
+
when="midnight",
|
|
211
|
+
backupCount=7,
|
|
212
|
+
encoding="utf-8",
|
|
213
|
+
)
|
|
214
|
+
file_handler.suffix = "%Y-%m-%d"
|
|
215
|
+
file_handler.setFormatter(
|
|
216
|
+
logging.Formatter(
|
|
217
|
+
fmt="%(asctime)s %(levelname)-10s %(message)s",
|
|
218
|
+
datefmt="%Y-%m-%d %H:%M:%S",
|
|
219
|
+
)
|
|
220
|
+
)
|
|
221
|
+
file_handler.addFilter(_DestinationFilter("to_file"))
|
|
222
|
+
self._logger.addHandler(file_handler)
|
|
223
|
+
|
|
224
|
+
def _log(
|
|
225
|
+
self,
|
|
226
|
+
level: int,
|
|
227
|
+
msg: str,
|
|
228
|
+
console: bool,
|
|
229
|
+
file: bool,
|
|
230
|
+
values: Mapping[str, object],
|
|
231
|
+
*,
|
|
232
|
+
exc_info: bool = False,
|
|
233
|
+
) -> None:
|
|
234
|
+
# `logging` interpola de forma perezosa: solo si el nivel está activo.
|
|
235
|
+
# `stacklevel=3` apunta al código que llamó a `info`, `error`...
|
|
236
|
+
self._logger.log(
|
|
237
|
+
level,
|
|
238
|
+
msg,
|
|
239
|
+
*([values] if values else []),
|
|
240
|
+
exc_info=exc_info,
|
|
241
|
+
extra={"to_console": console, "to_file": file},
|
|
242
|
+
stacklevel=3,
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
if __name__ == "__main__":
|
|
247
|
+
log = Logger(name="test")
|
|
248
|
+
log.info("Información")
|
|
249
|
+
log.error("Errores")
|
|
File without changes
|