custom-python-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.
File without changes
@@ -0,0 +1,149 @@
1
+ # logger.py
2
+
3
+ import logging
4
+ import os
5
+ import time
6
+ from logging import LoggerAdapter, Logger
7
+ from pathlib import Path
8
+ from typing import Optional, Any
9
+ from colorlog import ColoredFormatter
10
+
11
+
12
+ def get_project_path(project_name: str) -> str:
13
+ current_path = Path(__file__).parent
14
+ while current_path != current_path.parent:
15
+ if str(current_path).endswith(f'/{project_name}'):
16
+ return str(current_path)
17
+ current_path = current_path.parent
18
+ raise FileNotFoundError(
19
+ f'Project "{project_name}" not found in any parent directories.\n'
20
+ f'Current path: {Path(__file__)}',
21
+ )
22
+
23
+
24
+ def print_before_logger(project_name: str) -> None:
25
+ main_string = f'Start "{project_name}" Process'
26
+
27
+ number_of_ladder = "#" * len(f"### {main_string} ###")
28
+ print(f"\n{number_of_ladder}")
29
+ print(f"### {main_string} ###")
30
+ print(f"{number_of_ladder}\n")
31
+ time.sleep(0.3)
32
+
33
+
34
+ class CustomLoggerAdapter(logging.LoggerAdapter):
35
+ def exception(self, msg: str, *args, **kwargs):
36
+ level_no = 45
37
+ logging.addLevelName(level_no, "EXCEPTION")
38
+ kwargs.setdefault('stacklevel', 2)
39
+ self.log(level_no, msg, *args, exc_info=True, **kwargs)
40
+
41
+ def step(self, msg: str, *args, **kwargs):
42
+ level_no = 25
43
+ logging.addLevelName(level_no, "STEP")
44
+ kwargs.setdefault('stacklevel', 2)
45
+ self.log(level_no, msg, *args, exc_info=False, **kwargs)
46
+
47
+
48
+ def configure_logging(
49
+ log_format: str,
50
+ utc: bool,
51
+ log_level: int = logging.INFO,
52
+ log_file: Optional[str] = None,
53
+ console_output: bool = True,
54
+ ) -> None:
55
+ """
56
+ Configure global logging settings.
57
+
58
+ Args:
59
+ log_level: Logging level (default: INFO)
60
+ log_format: Format string for log messages
61
+ log_file: Path to log file (if None, no file logging)
62
+ console_output: Whether to output logs to console
63
+ utc: Whether to use UTC time for log timestamps
64
+ """
65
+ if utc:
66
+ logging.Formatter.converter = time.gmtime
67
+
68
+ root_logger = logging.getLogger()
69
+ root_logger.setLevel(log_level)
70
+
71
+ # Clear existing handlers
72
+ for handler in root_logger.handlers[:]:
73
+ root_logger.removeHandler(handler)
74
+
75
+ # Add file handler if specified
76
+ if log_file is not None:
77
+ log_file_formatter = logging.Formatter(log_format)
78
+
79
+ # Create directory if it doesn't exist
80
+ log_dir = os.path.dirname(log_file)
81
+ if log_dir and not os.path.exists(log_dir):
82
+ os.makedirs(log_dir)
83
+
84
+ file_handler = logging.FileHandler(log_file)
85
+
86
+ file_handler.setFormatter(log_file_formatter)
87
+ root_logger.addHandler(file_handler)
88
+
89
+ # Add console handler if specified
90
+ if console_output:
91
+ # log_console_formatter = logging.Formatter('%(log_color)s ' + log_format)
92
+ log_console_formatter = ColoredFormatter(
93
+ '%(log_color)s ' + log_format,
94
+ log_colors={
95
+ 'DEBUG': 'white',
96
+ 'INFO': 'green',
97
+ 'WARNING': 'yellow',
98
+ 'STEP': 'blue',
99
+ 'ERROR': 'red,bold',
100
+ 'EXCEPTION': 'light_red,bold',
101
+ 'CRITICAL': 'red,bg_white',
102
+ }
103
+ )
104
+
105
+ console_handler = logging.StreamHandler()
106
+ console_handler.setFormatter(log_console_formatter)
107
+ root_logger.addHandler(console_handler)
108
+
109
+
110
+ def get_logger(
111
+ project_name: str,
112
+ extra: Optional[dict[str, Any]] = None,
113
+ log_format: str = "%(asctime)s | %(levelname)-10s(l.%(levelno)s) | %(filename)s:%(lineno)s | %(message)s",
114
+ log_level: int = logging.INFO,
115
+ log_file: str = None,
116
+ console_output: bool = True,
117
+ utc: bool = False,
118
+ ) -> CustomLoggerAdapter[Logger | LoggerAdapter[Any] | Any] | Logger:
119
+ """
120
+ Get a named logger with optional extra context.
121
+
122
+ Args:
123
+ project_name: Name of the project
124
+ log_level: Optional specific log level
125
+ extra: Optional dictionary of extra context values
126
+ log_format: Format string for log messages
127
+ log_file: Path to log file (if None, no file logging)
128
+ console_output: Whether to output logs to console
129
+ utc: Whether to use UTC time for log timestamps
130
+
131
+ Returns:
132
+ Configured logger
133
+ """
134
+ print_before_logger(project_name=project_name)
135
+
136
+ configure_logging(
137
+ log_level=logging.DEBUG,
138
+ log_format=log_format,
139
+ log_file=log_file,
140
+ console_output=console_output,
141
+ utc=utc
142
+ )
143
+
144
+ logger = logging.getLogger()
145
+
146
+ if log_level is not None:
147
+ logger.setLevel(log_level)
148
+
149
+ return CustomLoggerAdapter(logger, extra)
@@ -0,0 +1,39 @@
1
+ import logging
2
+
3
+
4
+ class LoggerTest:
5
+ def __init__(self):
6
+ self.logger = logging.getLogger(self.__class__.__name__)
7
+
8
+ def main(self):
9
+ self.logger.info('Hello World')
10
+ self.logger.debug('Hello World')
11
+
12
+
13
+ def main():
14
+ from custom_python_logger.logger import get_logger
15
+
16
+ logger = get_logger(
17
+ project_name='Logger Project Test',
18
+ log_level=logging.DEBUG,
19
+ # extra={'user': 'test_user'}
20
+ )
21
+
22
+ logger.debug("This is a debug message.")
23
+ logger.info("This is an info message.")
24
+ logger.step("This is a step message.")
25
+ logger.warning("This is a warning message.")
26
+
27
+ try:
28
+ _ = 1 / 0
29
+ except ZeroDivisionError:
30
+ logger.exception("This is an exception message.")
31
+
32
+ logger.critical("This is a critical message.")
33
+
34
+ logger_test = LoggerTest()
35
+ logger_test.main()
36
+
37
+
38
+ if __name__ == '__main__':
39
+ main()
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: custom-python-logger
3
+ Version: 0.1.0
4
+ Summary: A custom logger with color support and additional features.
5
+ Home-page: https://github.com/aviz92/custom-python-logger
6
+ Author: Avi Zaguri
7
+ Author-email:
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.7
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: colorlog>=4.0.0
16
+ Requires-Dist: setuptools>=42.0.0
17
+ Requires-Dist: wheel>=0.36.2
18
+ Requires-Dist: colorlog>=6.7.0
19
+ Requires-Dist: pytest>=6.2.4
20
+ Requires-Dist: pathlib>=1.0.1
21
+ Dynamic: author
22
+ Dynamic: classifier
23
+ Dynamic: description
24
+ Dynamic: description-content-type
25
+ Dynamic: home-page
26
+ Dynamic: license-file
27
+ Dynamic: requires-dist
28
+ Dynamic: requires-python
29
+ Dynamic: summary
30
+
31
+ # Custom Logger
32
+ A Python logger with colored output and additional log levels. <br>
33
+ The logger supports custom log levels like `STEP` and `EXCEPTION` and can be easily integrated into your Python projects.
34
+
35
+ ## Installation
36
+ You can install the package using pip:
37
+ ```bash
38
+ pip install custom-python-logger
39
+ ```
40
+
41
+ ## Usage
42
+ please see the [usage_example](custom_python_logger/usage_example.py) file for more details.
@@ -0,0 +1,8 @@
1
+ custom_python_logger/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ custom_python_logger/logger.py,sha256=iwc5FzFszqZ7J9LaywQrcRi8H4NZnJ9GNOM5C-Dt82Y,4611
3
+ custom_python_logger/usage_example.py,sha256=pZixjxVJCgqK8j-KsWgtZ3I_TlpRhkEOvZ1rPV96py4,887
4
+ custom_python_logger-0.1.0.dist-info/licenses/LICENSE,sha256=cSikHY6SZFsPZSBizCDAJ0-Bjjzxt-JtX6TVbKxwimo,1067
5
+ custom_python_logger-0.1.0.dist-info/METADATA,sha256=EeAs5gwTalO-TZXDQO2wBRgDYu0nuDqxdodp9f8qwPQ,1299
6
+ custom_python_logger-0.1.0.dist-info/WHEEL,sha256=GHB6lJx2juba1wDgXDNlMTyM13ckjBMKf-OnwgKOCtA,91
7
+ custom_python_logger-0.1.0.dist-info/top_level.txt,sha256=lMihLuDQUTn0aSzzzbv9LZZTWTAap0IKpKabUHwOgks,21
8
+ custom_python_logger-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.3.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Avi Zaguri
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
+ custom_python_logger