nvlogger 0.1.0__py3-none-any.whl

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.
nvlogger/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """
2
+ nvlogger - Logging bonito e zero configuração para Python.
3
+
4
+ A modern, minimalist logging library that makes terminal output
5
+ beautiful using the rich library.
6
+
7
+ Example:
8
+ >>> from nvlogger import setup, log, success, info, warning, error, debug
9
+ >>> setup()
10
+ >>> log("Normal message")
11
+ >>> success("Operation completed!")
12
+ >>> info("Starting download...")
13
+ >>> warning("Large file detected")
14
+ >>> error("Connection failed", exc_info=True)
15
+ >>> debug("Debug info")
16
+ >>>
17
+ >>> # Using sections
18
+ >>> with log.section("Processing"):
19
+ ... log("Working...")
20
+ ... success("Done!")
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from .__version__ import __version__
26
+ from .setup import setup
27
+ from .core import log, success, info, warning, error, debug
28
+ from .context import section
29
+
30
+ # Attach section method to log function for log.section() syntax
31
+ log.section = section # type: ignore[attr-defined]
32
+
33
+ __all__ = [
34
+ "__version__",
35
+ "setup",
36
+ "log",
37
+ "success",
38
+ "info",
39
+ "warning",
40
+ "error",
41
+ "debug",
42
+ "section",
43
+ ]
@@ -0,0 +1,3 @@
1
+ """nvlogger version information."""
2
+
3
+ __version__ = "0.1.0"
nvlogger/context.py ADDED
@@ -0,0 +1,52 @@
1
+ """
2
+ nvlogger context manager module.
3
+
4
+ Provides the Section context manager for grouping log messages.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from contextlib import contextmanager
10
+ from typing import Generator
11
+
12
+ from rich.panel import Panel
13
+
14
+ from .setup import get_console
15
+
16
+
17
+ @contextmanager
18
+ def section(title: str) -> Generator[None, None, None]:
19
+ """
20
+ Context manager for creating a visual section in logs.
21
+
22
+ Creates a panel-like section with a title, visually grouping
23
+ all log messages within the context.
24
+
25
+ Args:
26
+ title: The title of the section.
27
+
28
+ Yields:
29
+ None
30
+
31
+ Example:
32
+ >>> from nvlogger import log, success
33
+ >>> with log.section("Processing"):
34
+ ... log("Loading data...")
35
+ ... success("Done!")
36
+ """
37
+ console = get_console()
38
+
39
+ # Print section header
40
+ console.print()
41
+ console.print(
42
+ f"[bold cyan]┌─[/bold cyan] [bold white]{title}[/bold white]",
43
+ )
44
+ console.print("[bold cyan]│[/bold cyan]")
45
+
46
+ try:
47
+ yield
48
+ finally:
49
+ # Print section footer
50
+ console.print("[bold cyan]│[/bold cyan]")
51
+ console.print("[bold cyan]└────────────────────[/bold cyan]")
52
+ console.print()
nvlogger/core.py ADDED
@@ -0,0 +1,248 @@
1
+ """
2
+ nvlogger core logging functions.
3
+
4
+ This module provides the main logging functions: log, success, info,
5
+ warning, error, and debug with beautiful colored output.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ import traceback
12
+ from datetime import datetime
13
+ from typing import Any, Optional
14
+
15
+ from rich.text import Text
16
+
17
+ from .setup import get_console, get_start_time, get_log_level
18
+
19
+
20
+ # Log level constants
21
+ LEVEL_DEBUG = 0
22
+ LEVEL_INFO = 1
23
+ LEVEL_WARNING = 2
24
+ LEVEL_ERROR = 3
25
+
26
+ # Style configuration for each log level
27
+ STYLES = {
28
+ "log": {
29
+ "emoji": "📝",
30
+ "color": "white",
31
+ "level": LEVEL_INFO,
32
+ },
33
+ "success": {
34
+ "emoji": "✅",
35
+ "color": "green",
36
+ "level": LEVEL_INFO,
37
+ },
38
+ "info": {
39
+ "emoji": "ℹ️",
40
+ "color": "blue",
41
+ "level": LEVEL_INFO,
42
+ },
43
+ "warning": {
44
+ "emoji": "⚠️",
45
+ "color": "yellow",
46
+ "level": LEVEL_WARNING,
47
+ },
48
+ "error": {
49
+ "emoji": "❌",
50
+ "color": "red",
51
+ "level": LEVEL_ERROR,
52
+ },
53
+ "debug": {
54
+ "emoji": "🔍",
55
+ "color": "dim",
56
+ "level": LEVEL_DEBUG,
57
+ },
58
+ }
59
+
60
+
61
+ def _format_relative_time(start_time: datetime) -> str:
62
+ """
63
+ Format the elapsed time since start as a relative string.
64
+
65
+ Args:
66
+ start_time: The reference start time.
67
+
68
+ Returns:
69
+ A human-readable relative time string in Portuguese.
70
+ """
71
+ delta = datetime.now() - start_time
72
+ seconds = int(delta.total_seconds())
73
+
74
+ if seconds < 1:
75
+ return "agora"
76
+ elif seconds < 60:
77
+ return f"há {seconds}s"
78
+ elif seconds < 3600:
79
+ minutes = seconds // 60
80
+ return f"há {minutes}min"
81
+ else:
82
+ hours = seconds // 3600
83
+ return f"há {hours}h"
84
+
85
+
86
+ def _format_kwargs(kwargs: dict[str, Any]) -> str:
87
+ """
88
+ Format extra keyword arguments for display.
89
+
90
+ Args:
91
+ kwargs: Dictionary of extra parameters.
92
+
93
+ Returns:
94
+ Formatted string of key=value pairs.
95
+ """
96
+ if not kwargs:
97
+ return ""
98
+
99
+ parts = [f"[dim]{k}=[/dim][italic]{v}[/italic]" for k, v in kwargs.items()]
100
+ return " " + " ".join(parts)
101
+
102
+
103
+ def _log_message(
104
+ message: str,
105
+ style_name: str,
106
+ exc_info: bool = False,
107
+ **kwargs: Any,
108
+ ) -> None:
109
+ """
110
+ Internal function to log a message with the specified style.
111
+
112
+ Args:
113
+ message: The message to log.
114
+ style_name: The style key (log, success, info, etc.).
115
+ exc_info: If True, include exception traceback.
116
+ **kwargs: Extra parameters to display.
117
+ """
118
+ style = STYLES[style_name]
119
+
120
+ # Check log level
121
+ if style["level"] < get_log_level():
122
+ return
123
+
124
+ console = get_console()
125
+ start_time = get_start_time()
126
+
127
+ # Format timestamp
128
+ timestamp = _format_relative_time(start_time)
129
+
130
+ # Format extra kwargs
131
+ extras = _format_kwargs(kwargs)
132
+
133
+ # Build the output
134
+ emoji = style["emoji"]
135
+ color = style["color"]
136
+
137
+ output = (
138
+ f"[dim]{timestamp:>8}[/dim] "
139
+ f"{emoji} "
140
+ f"[{color}]{message}[/{color}]"
141
+ f"{extras}"
142
+ )
143
+
144
+ console.print(output)
145
+
146
+ # Handle exception info
147
+ if exc_info:
148
+ exc_type, exc_value, exc_tb = sys.exc_info()
149
+ if exc_type is not None:
150
+ tb_lines = traceback.format_exception(exc_type, exc_value, exc_tb)
151
+ console.print()
152
+ console.print("[red]" + "".join(tb_lines) + "[/red]")
153
+
154
+
155
+ def log(message: str, **kwargs: Any) -> None:
156
+ """
157
+ Log a generic message.
158
+
159
+ Args:
160
+ message: The message to log.
161
+ **kwargs: Extra parameters to display (e.g., user="joao").
162
+
163
+ Example:
164
+ >>> log("Processing started")
165
+ >>> log("User action", user="joao", action="login")
166
+ """
167
+ _log_message(message, "log", **kwargs)
168
+
169
+
170
+ def success(message: str, **kwargs: Any) -> None:
171
+ """
172
+ Log a success message (green with ✅ emoji).
173
+
174
+ Args:
175
+ message: The success message.
176
+ **kwargs: Extra parameters to display.
177
+
178
+ Example:
179
+ >>> success("Operation completed successfully!")
180
+ >>> success("File saved", filename="data.json")
181
+ """
182
+ _log_message(message, "success", **kwargs)
183
+
184
+
185
+ def info(message: str, **kwargs: Any) -> None:
186
+ """
187
+ Log an informational message (blue with ℹ️ emoji).
188
+
189
+ Args:
190
+ message: The info message.
191
+ **kwargs: Extra parameters to display.
192
+
193
+ Example:
194
+ >>> info("Starting download...")
195
+ >>> info("Connecting to server", host="localhost")
196
+ """
197
+ _log_message(message, "info", **kwargs)
198
+
199
+
200
+ def warning(message: str, **kwargs: Any) -> None:
201
+ """
202
+ Log a warning message (yellow with ⚠️ emoji).
203
+
204
+ Args:
205
+ message: The warning message.
206
+ **kwargs: Extra parameters to display.
207
+
208
+ Example:
209
+ >>> warning("Large file detected")
210
+ >>> warning("Slow response", latency_ms=500)
211
+ """
212
+ _log_message(message, "warning", **kwargs)
213
+
214
+
215
+ def error(message: str, exc_info: bool = False, **kwargs: Any) -> None:
216
+ """
217
+ Log an error message (red with ❌ emoji).
218
+
219
+ Args:
220
+ message: The error message.
221
+ exc_info: If True, include the current exception traceback.
222
+ **kwargs: Extra parameters to display.
223
+
224
+ Example:
225
+ >>> error("Connection failed")
226
+ >>> try:
227
+ ... risky_operation()
228
+ ... except Exception:
229
+ ... error("Operation failed", exc_info=True)
230
+ """
231
+ _log_message(message, "error", exc_info=exc_info, **kwargs)
232
+
233
+
234
+ def debug(message: str, **kwargs: Any) -> None:
235
+ """
236
+ Log a debug message (gray with 🔍 emoji).
237
+
238
+ Only displayed when log level is DEBUG.
239
+
240
+ Args:
241
+ message: The debug message.
242
+ **kwargs: Extra parameters to display.
243
+
244
+ Example:
245
+ >>> debug("Variable state", x=42, y=3.14)
246
+ >>> debug(f"Intermediate value: {result:.2f}")
247
+ """
248
+ _log_message(message, "debug", **kwargs)
nvlogger/setup.py ADDED
@@ -0,0 +1,110 @@
1
+ """
2
+ nvlogger setup and configuration module.
3
+
4
+ This module provides the setup() function for initializing the logging system.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from datetime import datetime
11
+ from typing import Optional
12
+
13
+ from rich.console import Console
14
+
15
+ # Global state
16
+ _console: Optional[Console] = None
17
+ _start_time: Optional[datetime] = None
18
+ _log_level: int = 1 # 0=DEBUG, 1=INFO, 2=WARNING, 3=ERROR
19
+
20
+ # Log level mapping
21
+ LOG_LEVELS = {
22
+ "DEBUG": 0,
23
+ "INFO": 1,
24
+ "WARNING": 2,
25
+ "ERROR": 3,
26
+ }
27
+
28
+
29
+ def get_console() -> Console:
30
+ """
31
+ Get the global Console instance.
32
+
33
+ Returns:
34
+ Console: The rich Console instance used for output.
35
+
36
+ Raises:
37
+ RuntimeError: If setup() has not been called.
38
+ """
39
+ global _console
40
+ if _console is None:
41
+ # Auto-setup if not initialized
42
+ setup()
43
+ return _console
44
+
45
+
46
+ def get_start_time() -> datetime:
47
+ """
48
+ Get the start time for relative timestamps.
49
+
50
+ Returns:
51
+ datetime: The time when setup() was called.
52
+ """
53
+ global _start_time
54
+ if _start_time is None:
55
+ _start_time = datetime.now()
56
+ return _start_time
57
+
58
+
59
+ def get_log_level() -> int:
60
+ """
61
+ Get the current log level.
62
+
63
+ Returns:
64
+ int: The current log level (0=DEBUG, 1=INFO, 2=WARNING, 3=ERROR).
65
+ """
66
+ return _log_level
67
+
68
+
69
+ def setup(
70
+ level: Optional[str] = None,
71
+ force_terminal: Optional[bool] = None,
72
+ no_color: bool = False,
73
+ ) -> None:
74
+ """
75
+ Configure the nvlogger logging system.
76
+
77
+ This function initializes the Console and sets up the logging level.
78
+ The log level can be set via the `level` parameter or the NVLOGGER_LEVEL
79
+ environment variable (DEBUG, INFO, WARNING, ERROR).
80
+
81
+ Args:
82
+ level: Log level string (DEBUG, INFO, WARNING, ERROR).
83
+ Defaults to NVLOGGER_LEVEL env var or INFO.
84
+ force_terminal: Force terminal output even when not a TTY.
85
+ no_color: Disable colored output.
86
+
87
+ Example:
88
+ >>> from nvlogger import setup
89
+ >>> setup() # Use defaults
90
+ >>> setup(level="DEBUG") # Enable debug messages
91
+ """
92
+ global _console, _start_time, _log_level
93
+
94
+ # Initialize console
95
+ _console = Console(
96
+ force_terminal=force_terminal,
97
+ no_color=no_color,
98
+ highlight=False,
99
+ )
100
+
101
+ # Set start time for relative timestamps
102
+ _start_time = datetime.now()
103
+
104
+ # Determine log level
105
+ if level is None:
106
+ level = os.environ.get("NVLOGGER_LEVEL", "INFO").upper()
107
+ else:
108
+ level = level.upper()
109
+
110
+ _log_level = LOG_LEVELS.get(level, 1)
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.4
2
+ Name: nvlogger
3
+ Version: 0.1.0
4
+ Summary: Logging bonito e zero configuração para Python
5
+ Author-email: NullVoid <joaovictorsoares1703@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/NullVoidDev/richlog
8
+ Project-URL: Repository, https://github.com/NullVoidDev/richlog
9
+ Project-URL: Documentation, https://github.com/NullVoidDev/richlog#readme
10
+ Keywords: logging,terminal,rich,colorful,beautiful
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Topic :: System :: Logging
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.8
25
+ Description-Content-Type: text/markdown
26
+ Requires-Dist: rich>=13.0.0
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
29
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
30
+
31
+ # 🌈 nvlogger
32
+
33
+ [![PyPI version](https://img.shields.io/pypi/v/nvlogger.svg)](https://pypi.org/project/nvlogger/)
34
+ [![Python versions](https://img.shields.io/pypi/pyversions/nvlogger.svg)](https://pypi.org/project/nvlogger/)
35
+ [![License](https://img.shields.io/pypi/l/nvlogger.svg)](https://github.com/NullVoidDev/nvlogger/blob/main/LICENSE)
36
+
37
+ > **Logging bonito e zero configuração para Python** ✨
38
+
39
+ Transforme seu terminal em uma experiência visual agradável. `nvlogger` substitui `print()` e logging básico com mensagens coloridas, emojis e formatação elegante — tudo com zero configuração.
40
+
41
+ ## 📦 Instalação
42
+
43
+ ```bash
44
+ pip install nvlogger
45
+ ```
46
+
47
+ ## 🚀 Uso Rápido
48
+
49
+ ```python
50
+ from nvlogger import setup, log, success, info, warning, error, debug
51
+
52
+ setup() # Configura tudo automaticamente
53
+
54
+ log("Mensagem normal")
55
+ success("Operação concluída com sucesso!")
56
+ info("Iniciando download...")
57
+ warning("Atenção: arquivo grande detectado")
58
+ error("Falha na conexão com a API")
59
+ debug("Valor intermediário: 42.50")
60
+ ```
61
+
62
+ **Saída:**
63
+
64
+ ```
65
+ agora 📝 Mensagem normal
66
+ agora ✅ Operação concluída com sucesso!
67
+ agora ℹ️ Iniciando download...
68
+ agora ⚠️ Atenção: arquivo grande detectado
69
+ agora ❌ Falha na conexão com a API
70
+ agora 🔍 Valor intermediário: 42.50
71
+ ```
72
+
73
+ ## 📋 Funcionalidades
74
+
75
+ ### 🎨 Cores e Emojis Automáticos
76
+
77
+ | Função | Emoji | Cor |
78
+ |-----------|-------|----------|
79
+ | `log()` | 📝 | Branco |
80
+ | `success()` | ✅ | Verde |
81
+ | `info()` | ℹ️ | Azul |
82
+ | `warning()` | ⚠️ | Amarelo |
83
+ | `error()` | ❌ | Vermelho |
84
+ | `debug()` | 🔍 | Cinza |
85
+
86
+ ### ⏱️ Timestamp Relativo
87
+
88
+ Cada mensagem mostra um timestamp relativo: `agora`, `há 2s`, `há 1min`, etc.
89
+
90
+ ### 📦 Variáveis Extras
91
+
92
+ Adicione contexto às suas mensagens:
93
+
94
+ ```python
95
+ log("Login realizado", user="joao", ip="192.168.1.1")
96
+ # agora 📝 Login realizado user=joao ip=192.168.1.1
97
+ ```
98
+
99
+ ### 🔴 Exceções Formatadas
100
+
101
+ Capture e exiba exceções de forma elegante:
102
+
103
+ ```python
104
+ try:
105
+ resultado = 1 / 0
106
+ except ZeroDivisionError:
107
+ error("Erro no cálculo", exc_info=True)
108
+ ```
109
+
110
+ ### 📦 Seções
111
+
112
+ Agrupe logs relacionados visualmente:
113
+
114
+ ```python
115
+ with log.section("Processamento de imagens"):
116
+ log("Carregando imagens...")
117
+ info("Processando 100 arquivos")
118
+ success("Concluído!")
119
+ ```
120
+
121
+ **Saída:**
122
+
123
+ ```
124
+ ┌─ Processamento de imagens
125
+
126
+ agora 📝 Carregando imagens...
127
+ agora ℹ️ Processando 100 arquivos
128
+ agora ✅ Concluído!
129
+
130
+ └────────────────────
131
+ ```
132
+
133
+ ## ⚙️ Configuração
134
+
135
+ ### Nível de Log
136
+
137
+ Controle quais mensagens são exibidas via variável de ambiente:
138
+
139
+ ```bash
140
+ # Mostra apenas WARNING e ERROR
141
+ set NVLOGGER_LEVEL=WARNING
142
+
143
+ # Mostra tudo incluindo DEBUG
144
+ set NVLOGGER_LEVEL=DEBUG
145
+ ```
146
+
147
+ Ou configure diretamente:
148
+
149
+ ```python
150
+ setup(level="DEBUG")
151
+ ```
152
+
153
+ ### Opções de setup()
154
+
155
+ ```python
156
+ setup(
157
+ level="INFO", # Nível de log (DEBUG, INFO, WARNING, ERROR)
158
+ force_terminal=True, # Força saída de terminal (útil em pipes)
159
+ no_color=False, # Desabilita cores
160
+ )
161
+ ```
162
+
163
+ ## 📄 Licença
164
+
165
+ MIT License - use à vontade! 🎉
166
+
167
+ ---
168
+
169
+ Feito com ❤️ usando [rich](https://github.com/Textualize/rich)
@@ -0,0 +1,9 @@
1
+ nvlogger/__init__.py,sha256=koVIEbZabre23qx4zUoM1-r7bk3Nkj6tVMB7fim_tCM,1118
2
+ nvlogger/__version__.py,sha256=N3KNGNLBjJ32dlG26XXZq_OBpBHTc3jV9SOwTJCtbYU,62
3
+ nvlogger/context.py,sha256=oxU0HbTbh7GlNRTXeiWahTMrvYmGOY8eWqmPxgjBSvk,1338
4
+ nvlogger/core.py,sha256=iK0GeUWQ1X5bCppuBgqbTfpk0n0p7J-2hIU-QTcqO9A,6248
5
+ nvlogger/setup.py,sha256=OdwQQ3w4eJ8DOYfE9BUsxIqnHM-CDQbyASisY65EJYE,2736
6
+ nvlogger-0.1.0.dist-info/METADATA,sha256=Twq4hEE81MjUlRhqju5f425QPxKX2AHe5Hb_F31dZM0,4697
7
+ nvlogger-0.1.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
8
+ nvlogger-0.1.0.dist-info/top_level.txt,sha256=2rdGq6uSU7PXWV2-5HxH1YN_sQPET1EzXk1RUUeXqMY,9
9
+ nvlogger-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.10.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ nvlogger