logab 0.0.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.
logab-0.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Nam Kha Nguyen
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,3 @@
1
+ include LICENSE
2
+ include README.md
3
+ recursive-include logab *.py
logab-0.0.0/PKG-INFO ADDED
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.4
2
+ Name: logab
3
+ Version: 0.0.0
4
+ Summary: A lightweight Python package for logging with auto-balance (ab) formatting.
5
+ Author-email: Nam Kha Nguyen <namkha1032@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 Nam Kha Nguyen
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Project-URL: Homepage, https://github.com/namkha1032/logab
28
+ Project-URL: Repository, https://github.com/namkha1032/logab
29
+ Requires-Python: >=3.8
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE
32
+ Dynamic: license-file
33
+
34
+ # logab
35
+ A lightweight Python package for better formatting.
36
+ ## Install
37
+ ```
38
+ pip install logab
39
+ ```
40
+ ## Usage
41
+ ```
42
+ pip install logab
43
+ ```
44
+ ## Demo
45
+ ![Alt Text](demo.gif)
logab-0.0.0/README.md ADDED
@@ -0,0 +1,12 @@
1
+ # logab
2
+ A lightweight Python package for better formatting.
3
+ ## Install
4
+ ```
5
+ pip install logab
6
+ ```
7
+ ## Usage
8
+ ```
9
+ pip install logab
10
+ ```
11
+ ## Demo
12
+ ![Alt Text](demo.gif)
@@ -0,0 +1 @@
1
+ from .log_utils import log_init, log_wrap
@@ -0,0 +1,167 @@
1
+ import logging
2
+ import os
3
+ import shutil
4
+ import time
5
+ import traceback
6
+ from contextlib import contextmanager
7
+
8
+
9
+ def log_init():
10
+ logger = logging.getLogger(__name__)
11
+ return logger
12
+
13
+ class NKFormatter(logging.Formatter):
14
+ attr_tup = [('process', 3), ('asctime', 23), ('levelname', 4), ('funcName', 8), ('pathname', 4), ('lineno', 2)]
15
+ max_lengths = {key:val for key, val in attr_tup}
16
+ def __init__(self, log_file):
17
+ self.log_file = log_file
18
+ super().__init__()
19
+ def pad(self, string, length, idx):
20
+ return string.ljust(length) if idx != 4 else string.rjust(length)
21
+ def rewrite_log(self):
22
+ bak_path = f"{self.log_file}.bak"
23
+ with open (bak_path, mode='w', encoding='utf-8') as file_backup:
24
+ bak_path = file_backup.name
25
+ with open (self.log_file, 'r', encoding='utf-8') as file_log:
26
+ for idx, line in enumerate(file_log):
27
+ line = line.strip()
28
+ if idx == 1:
29
+ hor_line = self.draw_horizontal_line()
30
+ file_backup.write(f"{hor_line}\n")
31
+ else:
32
+ attr_list =line.split("|")
33
+ newline_arr = []
34
+ for attr_idx, attr in enumerate(attr_list[:-1]):
35
+ if attr_idx == 4:
36
+ lo_li_arr = attr.strip().split(":")
37
+ new_li = lo_li_arr[0].rjust(self.max_lengths[self.attr_tup[4][0]])
38
+ new_lo = lo_li_arr[1].ljust(self.max_lengths[self.attr_tup[5][0]])
39
+ newline_arr.append(f"{new_li}:{new_lo}")
40
+ else:
41
+ attr = attr.strip()
42
+ attr = attr.ljust(self.max_lengths[self.attr_tup[attr_idx][0]] + (1 if idx == 0 and attr_idx == 2 else 0))
43
+ newline_arr.append(attr)
44
+ newline_arr.append(attr_list[-1].strip())
45
+ file_backup.write(f"{' | '.join(newline_arr)}\n")
46
+
47
+
48
+ try:
49
+ shutil.copyfile(bak_path, self.log_file)
50
+ os.remove(bak_path)
51
+ except Exception as e:
52
+ pass
53
+ pass
54
+
55
+ @classmethod
56
+ def draw_horizontal_line(cls, placement="+"):
57
+ length = sum(cls.max_lengths.values()) + 3*6 + 7
58
+ hor_arr = ['-'*(cls.max_lengths[item[0]] + (1 if item[0] == 'levelname' else 0)) for item in cls.attr_tup]
59
+ hor_arr[4] = hor_arr[4] + hor_arr[5] + '-'
60
+ hor_arr.pop()
61
+ hor_arr.append('-'*40)
62
+ hor_line = f'-{placement}-'.join(hor_arr)
63
+ return hor_line
64
+
65
+
66
+
67
+
68
+ def format(self, record):
69
+ rewrite = False
70
+ abs_path = record.pathname
71
+ rel_path = os.path.relpath(abs_path, start=os.getcwd())
72
+ lib_name = "logab"
73
+ # rel_path = rel_path.replace("/", " / ")
74
+ record.pathname = rel_path if record.module != "log_utils" else lib_name
75
+ record.lineno = record.lineno if record.pathname != lib_name else 0
76
+
77
+ # Debug level emoji
78
+ level_emoji = {
79
+ "DEBUG": "🟢",
80
+ "INFO": "🔵",
81
+ "WARNING": "🟡",
82
+ "ERROR": "🔴",
83
+ "CRITICAL": "🟣"
84
+ }
85
+ record.levelname = f"{level_emoji[record.levelname]} {record.levelname.lower()}"
86
+ # Calculating max length
87
+ for field in self.max_lengths:
88
+ newlen = len(str(getattr(record, field, '')))
89
+ # + (1 if field == 'levelname' else 0)
90
+ if self.max_lengths[field] < newlen:
91
+ rewrite = True
92
+ self.max_lengths[field] = max(self.max_lengths[field], newlen)
93
+ if rewrite:
94
+ self.rewrite_log()
95
+
96
+ self._style._fmt = (
97
+ f'%(process){self.max_lengths["process"]}d | '
98
+ f'%(asctime){self.max_lengths["asctime"]}s | '
99
+ f'%(levelname)-{self.max_lengths["levelname"]}s | '
100
+ f'%(funcName)-{self.max_lengths["funcName"]}s | '
101
+ f'%(pathname){self.max_lengths["pathname"]}s:%(lineno)-{self.max_lengths["lineno"]}d | '
102
+ f'%(message)s'
103
+ )
104
+
105
+ return super().format(record)
106
+
107
+
108
+ def format_seconds(seconds):
109
+ if seconds <= 0:
110
+ return "0 seconds"
111
+
112
+ units = [
113
+ ("day", 86400), # 24 * 60 * 60
114
+ ("hour", 3600), # 60 * 60
115
+ ("minute", 60),
116
+ ("second", 1)
117
+ ]
118
+
119
+ result = []
120
+ remaining = float(seconds)
121
+
122
+ for unit_name, unit_seconds in units[:-1]:
123
+ if remaining >= unit_seconds:
124
+ value = int(remaining // unit_seconds)
125
+ remaining = remaining % unit_seconds
126
+ result.append(f"{value} {unit_name}{'s' if value > 1 else ''}")
127
+
128
+ if remaining > 0 or not result:
129
+ if remaining.is_integer():
130
+ result.append(f"{int(remaining)} second{'s' if remaining != 1 else ''}")
131
+ else:
132
+ result.append(f"{remaining:.4f} seconds".rstrip('0').rstrip('.'))
133
+
134
+ return " ".join(result)
135
+
136
+ @contextmanager
137
+ def log_wrap(log_file='./app.log', log_level="notset"):
138
+ log_level=getattr(logging, log_level.upper(), logging.NOTSET)
139
+ handler = logging.FileHandler(log_file, mode='a', encoding='utf-8')
140
+ formatter = NKFormatter(log_file)
141
+ handler.setFormatter(formatter)
142
+ root_logger = logging.getLogger()
143
+ root_logger.setLevel(log_level)
144
+ root_logger.addHandler(handler)
145
+ with open (log_file, 'w', encoding='utf-8') as file:
146
+ newstr = """PID | Time | Level | Function | File:No | Message\n."""
147
+ file.write(newstr)
148
+ start_time = time.time()
149
+ root_logger.info("Program starts...")
150
+ try:
151
+ yield
152
+ except Exception as e:
153
+ tb = traceback.format_exc()
154
+ root_logger.error(e)
155
+ with open(log_file, 'a', encoding='utf-8') as file:
156
+ hor_line = formatter.draw_horizontal_line(placement='+')
157
+ file.write(f"{hor_line}\n")
158
+ file.write(tb)
159
+
160
+ exit()
161
+ finally:
162
+ hor_line = formatter.draw_horizontal_line(placement='+')
163
+ with open(log_file, 'a', encoding='utf-8') as file:
164
+ file.write(f"{hor_line}\n")
165
+ end_time = time.time()
166
+ root_logger.info(f"Execution time {format_seconds(end_time-start_time)}")
167
+
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.4
2
+ Name: logab
3
+ Version: 0.0.0
4
+ Summary: A lightweight Python package for logging with auto-balance (ab) formatting.
5
+ Author-email: Nam Kha Nguyen <namkha1032@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 Nam Kha Nguyen
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Project-URL: Homepage, https://github.com/namkha1032/logab
28
+ Project-URL: Repository, https://github.com/namkha1032/logab
29
+ Requires-Python: >=3.8
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE
32
+ Dynamic: license-file
33
+
34
+ # logab
35
+ A lightweight Python package for better formatting.
36
+ ## Install
37
+ ```
38
+ pip install logab
39
+ ```
40
+ ## Usage
41
+ ```
42
+ pip install logab
43
+ ```
44
+ ## Demo
45
+ ![Alt Text](demo.gif)
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ logab/__init__.py
6
+ logab/log_utils.py
7
+ logab.egg-info/PKG-INFO
8
+ logab.egg-info/SOURCES.txt
9
+ logab.egg-info/dependency_links.txt
10
+ logab.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ logab
@@ -0,0 +1,21 @@
1
+ [project]
2
+ name = "logab"
3
+ version = "0.0.0"
4
+ description = "A lightweight Python package for logging with auto-balance (ab) formatting."
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Nam Kha Nguyen", email = "namkha1032@gmail.com" }
8
+ ]
9
+ license = { file = "LICENSE" }
10
+ requires-python = ">=3.8"
11
+
12
+ [project.urls]
13
+ Homepage = "https://github.com/namkha1032/logab"
14
+ Repository = "https://github.com/namkha1032/logab"
15
+
16
+ [build-system]
17
+ requires = ["setuptools>=61.0", "wheel"]
18
+ build-backend = "setuptools.build_meta"
19
+
20
+ [tool.setuptools]
21
+ packages = ["logab"]
logab-0.0.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+