python-fast-logger 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.
@@ -0,0 +1,43 @@
1
+ """
2
+ Fast Logger - A simple, no-fuss logging setup for Python applications.
3
+
4
+ This package provides a quick and easy way to set up logging in Python applications
5
+ with sensible defaults, rotating file handlers, and console output.
6
+
7
+ Basic usage:
8
+ from fast_logger import get_logger
9
+
10
+ logger = get_logger("my_app")
11
+ logger.info("Hello, world!")
12
+
13
+ Quick setup:
14
+ from fast_logger import quick_logger
15
+
16
+ logger = quick_logger("my_app")
17
+ logger.info("Hello, world!")
18
+
19
+ Advanced usage:
20
+ from fast_logger import FastLogger
21
+
22
+ logger = FastLogger(
23
+ name="my_app",
24
+ level="DEBUG",
25
+ max_file_size_mb=100,
26
+ backup_count=5
27
+ )
28
+ logger.info("Hello, world!")
29
+ """
30
+
31
+ from .core import FastLogger, setup_logger, get_logger, quick_logger
32
+
33
+ __version__ = "0.1.0"
34
+ __author__ = "Ravi Mishra"
35
+ __email__ = "ravi@paisafintech.com"
36
+
37
+ __all__ = [
38
+ "FastLogger",
39
+ "setup_logger",
40
+ "get_logger",
41
+ "quick_logger",
42
+ "__version__",
43
+ ]
fast_logger/core.py ADDED
@@ -0,0 +1,187 @@
1
+ """
2
+ Fast Logger - A simple, no-fuss logging setup for Python applications
3
+ """
4
+
5
+ import logging
6
+ import sys
7
+ from logging.handlers import RotatingFileHandler
8
+ from pathlib import Path
9
+ from typing import Optional, Union
10
+
11
+
12
+ class FastLogger:
13
+ """A simple logger setup with sensible defaults."""
14
+
15
+ def __init__(self,
16
+ name: str,
17
+ level: Union[int, str] = logging.INFO,
18
+ log_folder: str = 'logs',
19
+ max_file_size_mb: int = 50,
20
+ backup_count: int = 3,
21
+ log_format: Optional[str] = None,
22
+ console_output: bool = True,
23
+ base_path: Optional[str] = None):
24
+ """
25
+ Initialize FastLogger with configuration.
26
+
27
+ Args:
28
+ name: Logger name (will be used as filename)
29
+ level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
30
+ log_folder: Directory name for log files
31
+ max_file_size_mb: Maximum size of each log file in MB
32
+ backup_count: Number of backup files to keep
33
+ log_format: Custom log format string
34
+ console_output: Whether to output to console
35
+ base_path: Base directory for logs (defaults to caller's directory)
36
+ """
37
+ self.name = name
38
+ self.level = self._parse_level(level)
39
+ self.log_folder = log_folder
40
+ self.max_file_size_mb = max_file_size_mb
41
+ self.backup_count = backup_count
42
+ self.console_output = console_output
43
+ self.base_path = base_path
44
+
45
+ # Default format
46
+ self.log_format = log_format or (
47
+ '%(asctime)s - %(name)s [%(filename)s:%(lineno)d] - '
48
+ '%(levelname)s - %(message)s'
49
+ )
50
+
51
+ self._logger = None
52
+ self._setup_logger()
53
+
54
+ @staticmethod
55
+ def _parse_level(level: Union[int, str]) -> int:
56
+ """Parse logging level from string or int."""
57
+ if isinstance(level, str):
58
+ return getattr(logging, level.upper(), logging.INFO)
59
+ return level
60
+
61
+ def _get_log_directory(self) -> Path:
62
+ """Get the log directory path."""
63
+ if self.base_path:
64
+ base = Path(self.base_path)
65
+ else:
66
+ # Use the directory of the calling script
67
+ import inspect
68
+ frame = inspect.currentframe()
69
+ try:
70
+ # Go up the stack to find the caller
71
+ caller_frame = frame.f_back.f_back.f_back # Go up one more level
72
+ caller_file = caller_frame.f_code.co_filename
73
+ base = Path(caller_file).parent
74
+ finally:
75
+ del frame
76
+
77
+ log_dir = base / self.log_folder
78
+ log_dir.mkdir(parents=True, exist_ok=True)
79
+ return log_dir
80
+
81
+ def _setup_logger(self):
82
+ """Set up the logger with file and console handlers."""
83
+ # Get or create logger
84
+ self._logger = logging.getLogger(self.name)
85
+
86
+ # Clear any existing handlers to avoid duplicates
87
+ self._logger.handlers.clear()
88
+ self._logger.setLevel(self.level)
89
+
90
+ # Create formatter
91
+ formatter = logging.Formatter(self.log_format)
92
+
93
+ # File handler
94
+ log_dir = self._get_log_directory()
95
+ log_file = log_dir / f"{self.name}.log"
96
+
97
+ file_handler = RotatingFileHandler(
98
+ str(log_file), # Convert Path to string
99
+ maxBytes=self.max_file_size_mb * 1024 * 1024,
100
+ backupCount=self.backup_count,
101
+ encoding='utf-8'
102
+ )
103
+ file_handler.setLevel(self.level)
104
+ file_handler.setFormatter(formatter)
105
+ self._logger.addHandler(file_handler)
106
+
107
+ # Console handler (only if enabled)
108
+ if self.console_output:
109
+ console_handler = logging.StreamHandler(sys.stdout)
110
+ console_handler.setLevel(self.level)
111
+ console_handler.setFormatter(formatter)
112
+ self._logger.addHandler(console_handler)
113
+
114
+ # Prevent propagation to root logger
115
+ self._logger.propagate = False
116
+
117
+ def get_logger(self) -> logging.Logger:
118
+ """Get the configured logger instance."""
119
+ return self._logger
120
+
121
+ def debug(self, message: str, *args, **kwargs):
122
+ """Log a debug message."""
123
+ self._logger.debug(message, *args, **kwargs)
124
+
125
+ def info(self, message: str, *args, **kwargs):
126
+ """Log an info message."""
127
+ self._logger.info(message, *args, **kwargs)
128
+
129
+ def warning(self, message: str, *args, **kwargs):
130
+ """Log a warning message."""
131
+ self._logger.warning(message, *args, **kwargs)
132
+
133
+ def error(self, message: str, *args, **kwargs):
134
+ """Log an error message."""
135
+ self._logger.error(message, *args, **kwargs)
136
+
137
+ def critical(self, message: str, *args, **kwargs):
138
+ """Log a critical message."""
139
+ self._logger.critical(message, *args, **kwargs)
140
+
141
+ def exception(self, message: str, *args, **kwargs):
142
+ """Log an exception with traceback."""
143
+ self._logger.exception(message, *args, **kwargs)
144
+
145
+
146
+ def setup_logger(name: str, **kwargs) -> logging.Logger:
147
+ """
148
+ Quick setup function for backward compatibility and convenience.
149
+
150
+ Args:
151
+ name: Logger name
152
+ **kwargs: Additional arguments passed to FastLogger
153
+
154
+ Returns:
155
+ Configured logger instance
156
+ """
157
+ fast_logger = FastLogger(name, **kwargs)
158
+ return fast_logger.get_logger()
159
+
160
+
161
+ def get_logger(name: str, **kwargs) -> FastLogger:
162
+ """
163
+ Get a FastLogger instance with fluent interface.
164
+
165
+ Args:
166
+ name: Logger name
167
+ **kwargs: Additional arguments passed to FastLogger
168
+
169
+ Returns:
170
+ FastLogger instance
171
+ """
172
+ return FastLogger(name, **kwargs)
173
+
174
+
175
+ # Convenience function for one-liner setup
176
+ def quick_logger(name: str, level: str = 'INFO') -> logging.Logger:
177
+ """
178
+ Super quick logger setup with minimal configuration.
179
+
180
+ Args:
181
+ name: Logger name
182
+ level: Logging level
183
+
184
+ Returns:
185
+ Configured logger instance
186
+ """
187
+ return setup_logger(name, level=level)
@@ -0,0 +1,232 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-fast-logger
3
+ Version: 0.1.0
4
+ Summary: A simple, no-fuss logging setup for Python applications
5
+ Author-email: Ravi Mishra <ravi@paisafintech.com>
6
+ Maintainer-email: Ravi Mishra <ravi@paisafintech.com>
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/RaviMishra-94/fast-logger
9
+ Project-URL: Documentation, https://github.com/RaviMishra-94/fast-logger/blob/main/README.md
10
+ Project-URL: Repository, https://github.com/RaviMishra-94/fast-logger.git
11
+ Project-URL: Bug Tracker, https://github.com/RaviMishra-94/fast-logger/issues
12
+ Keywords: logging,logger,simple,fast,rotating,file
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.7
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Topic :: System :: Logging
26
+ Requires-Python: >=3.7
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=6.0; extra == "dev"
31
+ Requires-Dist: pytest-cov>=2.0; extra == "dev"
32
+ Requires-Dist: black>=21.0; extra == "dev"
33
+ Requires-Dist: flake8>=3.8; extra == "dev"
34
+ Requires-Dist: mypy>=0.800; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ # Fast Logger
38
+
39
+ ![Tests](https://github.com/RaviMishra-94/fast-logger/actions/workflows/python-app.yml/badge.svg)
40
+
41
+ A simple, no-fuss logging setup for Python applications with sensible defaults.
42
+
43
+ ## Features
44
+
45
+ - **Zero configuration**: Works out of the box with sensible defaults
46
+ - **Rotating file logs**: Automatically manages log file sizes and backups
47
+ - **Console output**: Simultaneous logging to file and console
48
+ - **Flexible configuration**: Easy to customize when needed
49
+ - **Type hints**: Full type hint support for better IDE experience
50
+ - **No dependencies**: Uses only Python standard library
51
+
52
+ ## Installation
53
+
54
+ ```bash
55
+ pip install fast-logger
56
+ ```
57
+
58
+ ## Quick Start
59
+
60
+ ### Super Simple Usage
61
+
62
+ ```python
63
+ from fast_logger import quick_logger
64
+
65
+ logger = quick_logger("my_app")
66
+ logger.info("Hello, world!")
67
+ logger.error("Something went wrong!")
68
+ ```
69
+
70
+ ### Basic Usage
71
+
72
+ ```python
73
+ from fast_logger import get_logger
74
+
75
+ logger = get_logger("my_app")
76
+ logger.info("Application started")
77
+ logger.warning("This is a warning")
78
+ logger.error("This is an error")
79
+ ```
80
+
81
+ ### Advanced Usage
82
+
83
+ ```python
84
+ from fast_logger import FastLogger
85
+
86
+ # Custom configuration
87
+ logger = FastLogger(
88
+ name="my_advanced_app",
89
+ level="DEBUG",
90
+ log_folder="custom_logs",
91
+ max_file_size_mb=100,
92
+ backup_count=5,
93
+ console_output=True
94
+ )
95
+
96
+ logger.info("Advanced logging setup complete")
97
+ logger.debug("Debug information")
98
+ ```
99
+
100
+ ### Web Application Example
101
+
102
+ ```python
103
+ from fast_logger import get_logger
104
+ from flask import Flask
105
+
106
+ app = Flask(__name__)
107
+ logger = get_logger("web_app", level="INFO")
108
+
109
+ @app.route("/")
110
+ def home():
111
+ logger.info("Home page accessed")
112
+ return "Hello, World!"
113
+
114
+ @app.route("/api/data")
115
+ def get_data():
116
+ try:
117
+ # Your API logic here
118
+ data = {"status": "success"}
119
+ logger.info("Data retrieved successfully")
120
+ return data
121
+ except Exception as e:
122
+ logger.error(f"Error retrieving data: {e}")
123
+ return {"status": "error"}, 500
124
+ ```
125
+
126
+ ## Configuration Options
127
+
128
+ | Parameter | Type | Default | Description |
129
+ |-----------|------|---------|-------------|
130
+ | `name` | str | Required | Logger name (used as filename) |
131
+ | `level` | str/int | `INFO` | Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL) |
132
+ | `log_folder` | str | `logs` | Directory name for log files |
133
+ | `max_file_size_mb` | int | `50` | Maximum size of each log file in MB |
134
+ | `backup_count` | int | `3` | Number of backup files to keep |
135
+ | `console_output` | bool | `True` | Whether to output to console |
136
+ | `log_format` | str | Default format | Custom log format string |
137
+ | `base_path` | str | Caller's directory | Base directory for logs |
138
+
139
+ ## Default Log Format
140
+
141
+ ```
142
+ 2024-01-15 10:30:45,123 - my_app [main.py:15] - INFO - Hello, world!
143
+ ```
144
+
145
+ ## File Structure
146
+
147
+ By default, logs are created in a `logs` folder relative to your script:
148
+
149
+ ```
150
+ your_project/
151
+ ├── main.py
152
+ └── logs/
153
+ ├── my_app.log
154
+ ├── my_app.log.1
155
+ └── my_app.log.2
156
+ ```
157
+
158
+ ## API Reference
159
+
160
+ ### FastLogger Class
161
+
162
+ The main class for advanced usage with full configuration options.
163
+
164
+ ```python
165
+ logger = FastLogger(
166
+ name="my_app",
167
+ level="INFO",
168
+ log_folder="logs",
169
+ max_file_size_mb=50,
170
+ backup_count=3,
171
+ console_output=True,
172
+ log_format=None,
173
+ base_path=None
174
+ )
175
+ ```
176
+
177
+ ### Convenience Functions
178
+
179
+ - `quick_logger(name, level="INFO")`: Minimal setup for immediate use
180
+ - `get_logger(name, **kwargs)`: Returns FastLogger instance with fluent interface
181
+ - `setup_logger(name, **kwargs)`: Returns standard logging.Logger instance
182
+
183
+ ## Why Fast Logger?
184
+
185
+ Most Python applications need logging, but setting it up properly requires boilerplate code:
186
+
187
+ - Creating formatters
188
+ - Setting up file handlers
189
+ - Configuring rotation
190
+ - Adding console output
191
+ - Managing log directories
192
+
193
+ Fast Logger eliminates this boilerplate while providing sensible defaults that work for most applications.
194
+
195
+ ## Comparison with Standard Logging
196
+
197
+ **Standard logging setup:**
198
+ ```python
199
+ import logging
200
+ import os
201
+ from logging.handlers import RotatingFileHandler
202
+
203
+ # 15+ lines of boilerplate code...
204
+ logger = logging.getLogger("my_app")
205
+ logger.setLevel(logging.INFO)
206
+ # ... more setup code
207
+ ```
208
+
209
+ **Fast Logger:**
210
+ ```python
211
+ from fast_logger import quick_logger
212
+
213
+ logger = quick_logger("my_app")
214
+ # Done!
215
+ ```
216
+
217
+ ## Requirements
218
+
219
+ - Python 3.7+
220
+ - No external dependencies
221
+
222
+ ## License
223
+
224
+ MIT License. See LICENSE file for details.
225
+
226
+ ## Contributing
227
+
228
+ Contributions are welcome! Please feel free to submit a Pull Request.
229
+
230
+ ## Changelog
231
+
232
+ See [CHANGELOG.md](CHANGELOG.md) for version history.
@@ -0,0 +1,7 @@
1
+ fast_logger/__init__.py,sha256=ZM2ZVkLa8Cp0JUpSJOGEFS4HFSJGcl7lI3YTj0tkUQI,963
2
+ fast_logger/core.py,sha256=VUSY4WzIF61mSSem8OCRUPwGhOP0hgGn7_USF0fr9VM,6021
3
+ python_fast_logger-0.1.0.dist-info/licenses/LICENSE,sha256=zUSVkLSqRvRAvbhtvLfGSC_Tw1ao2TsxwwvHr05VydQ,1067
4
+ python_fast_logger-0.1.0.dist-info/METADATA,sha256=63x7SrKum1vdwoCw7gHNiqom9mgztexFwJrWrAaeq2M,6149
5
+ python_fast_logger-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
6
+ python_fast_logger-0.1.0.dist-info/top_level.txt,sha256=c9NyRn7UsQxVnCzh3hCbwdUmz3kH-7-bWODGfANcGsw,12
7
+ python_fast_logger-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Ravi Mishra
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.
@@ -0,0 +1 @@
1
+ fast_logger