Skip to content

Commit fc01a56

Browse files
committed
Move coloring from logger to read
1 parent 12e99b9 commit fc01a56

File tree

5 files changed

+45
-40
lines changed

5 files changed

+45
-40
lines changed

.gitignore

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
__pycache__
1+
__pycache__/
22
poetry.lock
33
dev.py

livelog/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
# -*- coding: utf-8 -*-
22

3-
from .logger import Logger
3+
from livelog.logger import Logger

livelog/__main__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from sys import argv
44
from os import _exit
5-
from .reader import start_reader
5+
from livelog.reader import start_reader
66

77
if __name__ == "__main__":
88
if len(argv) == 1:

livelog/logger.py

+9-27
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def __new__(cls, *args, **kwargs):
3232
def __init__(
3333
self,
3434
output_file: str = None,
35-
level: str = "INFO",
35+
level: str = "DEBUG",
3636
enabled: bool = True,
3737
colors: bool = True,
3838
erase: bool = True,
@@ -42,7 +42,7 @@ def __init__(
4242
4343
Args:
4444
output_file (str, optional): Output file path. Defaults to None.
45-
level (str, optional): Minimum log level. Defaults to "INFO".
45+
level (str, optional): Minimum log level. Defaults to "DEBUG".
4646
enabled (bool, optional): Is log enabled ? Defaults to True.
4747
colors (bool, optional): Are colors enabled ? Defaults to True.
4848
erase (bool, optional): Should preexisting file be erased ? Defaults to True.
@@ -116,7 +116,7 @@ def _clear_file(self):
116116
with open(self._output_file, "w") as f:
117117
pass
118118

119-
def _write(self, content: str):
119+
def _write(self, level: str, content: str):
120120
"""Write provided content to output file.
121121
122122
Args:
@@ -126,16 +126,10 @@ def _write(self, content: str):
126126
if not self._enabled:
127127
return
128128

129-
if self._colors:
130-
time = Style.DIM + datetime.now().strftime("%H:%M:%S.%f")[:-3]
131-
dash = Style.BRIGHT + " - "
132-
content = f"{Style.NORMAL}{content}{Style.RESET_ALL}"
133-
else:
134-
time = datetime.now().strftime("%H:%M:%S.%f")[:-3]
135-
dash = " - "
129+
time = datetime.now().strftime("%H:%M:%S.%f")[:-3]
136130

137131
with open(self._output_file, "a") as f:
138-
f.write(f"{time}{dash}{content}\n")
132+
f.write(f"{level} | {time} - {content}\n")
139133

140134
def _is_valid_level(self, level: str):
141135
"""Verify if the given log level should be written.
@@ -156,10 +150,7 @@ def error(self, message: str):
156150
message (str): Log message
157151
"""
158152

159-
if self._colors:
160-
self._write(content=Fore.RED + message)
161-
else:
162-
self._write(content="error | " + message)
153+
self._write(level="ERR!", content=message)
163154

164155
def warn(self, message: str):
165156
"""Write warning message.
@@ -170,10 +161,7 @@ def warn(self, message: str):
170161

171162
if not self._is_valid_level("WARNING"):
172163
return
173-
if self._colors:
174-
self._write(content=Fore.YELLOW + message)
175-
else:
176-
self._write(content="warning | " + message)
164+
self._write(level="WARN", content=message)
177165

178166
def info(self, message: str):
179167
"""Write info message.
@@ -184,10 +172,7 @@ def info(self, message: str):
184172

185173
if not self._is_valid_level("INFO"):
186174
return
187-
if self._colors:
188-
self._write(content=Fore.BLUE + message)
189-
else:
190-
self._write(content="info | " + message)
175+
self._write(level="INFO", content=message)
191176

192177
def debug(self, message: str):
193178
"""Write debug message.
@@ -198,7 +183,4 @@ def debug(self, message: str):
198183

199184
if not self._is_valid_level("DEBUG"):
200185
return
201-
if self._colors:
202-
self._write(content=Fore.WHITE + message)
203-
else:
204-
self._write(content="debug | " + message)
186+
self._write(level="DBUG", content=message)

livelog/reader.py

+33-10
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,15 @@
55
from shutil import get_terminal_size
66
from watchdog.observers import Observer
77
from watchdog.events import FileSystemEventHandler, DirModifiedEvent, FileModifiedEvent
8-
from colorama import Style
8+
from colorama import Style, Fore
9+
10+
CLEAR_CMD = "cls" if name == "nt" else "clear"
11+
12+
13+
def clear():
14+
"""Clear terminal."""
15+
16+
system(CLEAR_CMD)
917

1018

1119
def tail(file_name: str, lines: int):
@@ -28,7 +36,28 @@ def tail(file_name: str, lines: int):
2836
finally:
2937
rows = list(f)
3038
pos *= 2
31-
print("".join(rows[-lines:]))
39+
40+
colored_lines = map(color_line, rows[-lines:])
41+
clear()
42+
print("".join(list(colored_lines)))
43+
44+
45+
LEVEL_COLORS = {
46+
"ERR!": Fore.RED,
47+
"WARN": Fore.YELLOW,
48+
"INFO": Fore.BLUE,
49+
"DBUG": Fore.WHITE,
50+
}
51+
52+
53+
def color_line(line: str):
54+
level = line[:4]
55+
56+
output = (
57+
f"{Style.DIM}{line[7:19]}{Style.BRIGHT} - {Style.NORMAL}"
58+
f"{LEVEL_COLORS[level]}{line[26:]}{Style.RESET_ALL}"
59+
)
60+
return output
3261

3362

3463
class ReadFile(FileSystemEventHandler):
@@ -44,22 +73,16 @@ def __init__(self, file: str):
4473
self._file = file
4574
self.on_modified(event=None)
4675

47-
def clear(self):
48-
"""Clear terminal."""
49-
50-
_ = system("cls") if name == "nt" else system("clear")
51-
5276
def on_modified(self, event: Union[DirModifiedEvent, FileModifiedEvent, None]):
5377
"""File modification callback.
5478
5579
Args:
5680
event (Union[DirModifiedEvent, FileModifiedEvent, None]): Watchdog event
5781
"""
5882

59-
self.clear()
60-
print(Style.RESET_ALL)
83+
print(Style.RESET_ALL, end="")
6184
tail(self._file, get_terminal_size(fallback=(120, 50))[1])
62-
print(Style.RESET_ALL)
85+
print(Style.RESET_ALL, end="")
6386

6487

6588
def start_reader(file: str):

0 commit comments

Comments
 (0)