Initial Commit

This commit is contained in:
Didier Slof 2022-07-29 02:27:43 +02:00
commit 0c1cb9f214
Signed by: didier
GPG key ID: 01E71F18AA4398E5
15 changed files with 277 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
venv/

8
.idea/.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View file

@ -0,0 +1,24 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredBaseClasses">
<list>
<option value="unittest.TestCase" />
<option value="unittest.case.TestCase" />
<option value="lib.Configs.GlobalConfig" />
</list>
</option>
</inspection_tool>
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredIdentifiers">
<list>
<option value="builtins.*" />
<option value="dict.samba_url" />
<option value="dict.username" />
<option value="dict.mount_point" />
</list>
</option>
</inspection_tool>
</profile>
</component>

View file

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

4
.idea/misc.xml Normal file
View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (pylogger)" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml Normal file
View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/pylogger.iml" filepath="$PROJECT_DIR$/.idea/pylogger.iml" />
</modules>
</component>
</project>

11
.idea/pylogger.iml Normal file
View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

6
.idea/vcs.xml Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

11
src/__init__.py Normal file
View file

@ -0,0 +1,11 @@
from lib import BaseLogger
from lib import Logger
_logger = None
def get_or_create_logger() -> Logger:
global _logger
if _logger is None:
_logger = Logger()
return _logger

36
src/lib/BaseLogger.py Normal file
View file

@ -0,0 +1,36 @@
from .Log import Log
from .LogLevels import basic_levels, Level
from .console import util
import inspect
class BaseLogger:
def __init__(self, name: str = "Generic", do_colors = True):
self.name = name
self.do_colors = do_colors
def _log(self, log: Log):
l_pre = f"{log.level.short} [{log.format_time('%Y-%m-%d %H:%M:%S')}] <{log.class_str() or log.file}>"
l_str = f"{log.format_text()}"
if self.do_colors:
print(f"{log.level.color}{l_pre}{util.reset} {l_str}")
else:
print(f'{l_pre} {l_str}')
def custom(self, level: Level, text: str, *args, _class=None, _file=inspect.stack()[1].filename):
self._log(Log(level, text, *args, _class=None, _file=inspect.stack()[1].filename))
def debug(self, text: str, *args, _class=None):
self._log(Log(basic_levels['DEBUG'], text, *args, _class=_class, _file=inspect.stack()[1].filename))
def info(self, text: str, *args, _class=None):
self._log(Log(basic_levels['INFO'], text, *args, _class=_class, _file=inspect.stack()[1].filename))
def warn(self, text: str, *args, _class=None):
self._log(Log(basic_levels['WARNING'], text, *args, _class=_class, _file=inspect.stack()[1].filename))
def err(self, text: str, *args, _class=None):
self._log(Log(basic_levels['ERROR'], text, *args, _class=_class, _file=inspect.stack()[1].filename))
def fatal(self, text: str, *args, _class=None):
self._log(Log(basic_levels['FATAL'], text, *args, _class=_class, _file=inspect.stack()[1].filename))

34
src/lib/Log.py Normal file
View file

@ -0,0 +1,34 @@
import datetime
import time
import inspect
from .LogLevels import Level
class Log:
def __init__(self, level: Level, text: str, *args, _class=None, _file=inspect.stack()[1].filename):
"""
Create a log message.
"""
self.level = level
self.text = text
self.args = args
self.created_on = time.time()
self.file = _file
self._class = _class
def format_time(self, fmt: str):
return datetime.datetime.fromtimestamp(self.created_on).strftime(fmt)
def class_str(self):
if self._class:
prefix = f'{type(self._class).__name__}'
if hasattr(self._class, 'name'):
prefix += ":"
prefix += self._class.name
return prefix
else:
return None
def format_text(self):
return f'{self.text.format(*self.args)}'

23
src/lib/LogLevels.py Normal file
View file

@ -0,0 +1,23 @@
from lib import console
class Level:
def __init__(self, name: str, weight: int, short_name: str or None = None, _color: str = console.fg.white):
"""
Create a logging level.
"""
self.name = name
self.weight = weight
self.color = _color
if short_name is None:
self.short = name.upper()[:1]
else:
self.short = short_name.upper()
basic_levels = {
'FATAL': Level('FATAL', 10, _color=(console.fg.red + console.util.bold)),
'ERROR': Level('ERROR', 3, _color=console.fg.red),
'WARNING': Level('WARNING', 2, _color=console.fg.yellow),
'INFO': Level('INFO', 1, _color=console.fg.blue),
'DEBUG': Level('DEBUG', 0, _color=console.fg.green)
}

4
src/lib/Logger.py Normal file
View file

@ -0,0 +1,4 @@
from .BaseLogger import BaseLogger
class Logger(BaseLogger):
pass

93
src/lib/console.py Normal file
View file

@ -0,0 +1,93 @@
from sys import stdout, stdin
from time import sleep
class fg:
black = "\u001b[30m"
red = "\u001b[31m"
green = "\u001b[32m"
yellow = "\u001b[33m"
blue = "\u001b[34m"
magenta = "\u001b[35m"
cyan = "\u001b[36m"
white = "\u001b[37m"
def rgb(r, g, b): return f"\u001b[38;2;{r};{g};{b}m"
class bg:
black = "\u001b[40m"
red = "\u001b[41m"
green = "\u001b[42m"
yellow = "\u001b[43m"
blue = "\u001b[44m"
magenta = "\u001b[45m"
cyan = "\u001b[46m"
white = "\u001b[47m"
def rgb(r, g, b): return f"\u001b[48;2;{r};{g};{b}m"
class util:
reset = "\u001b[0m"
bold = "\u001b[1m"
underline = "\u001b[4m"
reverse = "\u001b[7m"
clear = "\u001b[2J"
clearline = "\u001b[2K"
up = "\u001b[1A"
down = "\u001b[1B"
right = "\u001b[1C"
left = "\u001b[1D"
nextline = "\u001b[1E"
prevline = "\u001b[1F"
top = "\u001b[0;0H"
def to(x, y):
return f"\u001b[{y};{x}H"
def write(text="\n"):
stdout.write(text)
stdout.flush()
def writew(text="\n", wait=0.5):
for char in text:
stdout.write(char)
stdout.flush()
sleep(wait)
def read(begin=""):
text = ""
stdout.write(begin)
stdout.flush()
while True:
char = ord(stdin.read(1))
if char == 3:
return
elif char in (10, 13):
return text
else:
text += chr(char)
def readw(begin="", wait=0.5):
text = ""
for char in begin:
stdout.write(char)
stdout.flush()
sleep(wait)
while True:
char = ord(stdin.read(1))
if char == 3:
return
elif char in (10, 13):
return text
else:
text += chr(char)

8
src/test.py Normal file
View file

@ -0,0 +1,8 @@
from lib.BaseLogger import BaseLogger
from lib.LogLevels import Level
from lib.Log import Log
from lib import console
_LOGGER = BaseLogger("Generic")
_LOGGER.info("Started Loco {}", "v1")