- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
#!/usr/bin/env python3
# -*- coding: UTF8 -*-
from datetime import date
from os import environ, mkdir, system
from os.path import dirname, exists, join as path_join
from time import time
def check_verbose():
return environ.get("DEBUG") in ("true", "True", "TRUE", True, "yes", "Yes", "YES")
class Timer:
def __init__(self):
"""
Объект добавляет в начале текста временные метки
"""
self.start_epoch = self.last_call = time()
@staticmethod
def __fully_scope(timer: int or str) -> str:
"""
Преобразует однозначные значения в двузначные.
:param timer: Время
:return: Двузначное значение
"""
if len(str(timer)) == 2:
return str(timer)
elif len(str(timer)) == 1:
return "0" + str(timer)
elif len(str(timer)) <= 0:
return "00"
elif len(str(timer)) >= 2:
return str(timer)[:2]
def __formatter(self, timestep: float) -> str:
"""
Форматирует время
:return: время hh:mm:ss
"""
_hours = int(timestep // 3600), int(timestep % 3600)
_minute = int(_hours[1] // 60), int(_hours[1] % 60)
_current_epoch = f"{self.__fully_scope(_minute[0])}:{self.__fully_scope(_minute[1])}"
if _hours[0] > 0:
_current_epoch = f"{_hours[0]}:" + _current_epoch
return _current_epoch
def __call__(self, fix_call: bool = True) -> str:
"""
Считает время с начала сценария + с последнего шага
:return: время hh:mm:ss(+hh:mm:ss)
"""
current_epoch = self.__formatter(time() - self.start_epoch)
timedelta_epoch = self.__formatter(time() - self.last_call)
if fix_call:
self.last_call = time()
return f"{current_epoch}(+{timedelta_epoch})"
def __bool__(self):
return True
class Logger:
def __init__(self, name: str):
self.start_time = time()
self.name = name.upper()
self.timer = Timer()
self.log_file = path_join(environ["RESULT_DIR"], name, f"{name}_{date.today().isoformat()}.log")
def check_file(self):
if not exists(self.log_file):
if not exists(dirname(self.log_file)):
mkdir(dirname(self.log_file))
system(f"echo {date.today().isoformat()}> {self.log_file}")
def save_log(self, msg: str):
self.check_file()
with open(self.log_file, "a+") as _log_file:
_log_file.write(msg + "\n")
def massage(self, msg: str):
print(f"{self.timer()}::{self.name}::{msg}")
self.check_file()
self.save_log(f"{self.timer()}::{self.name}::{msg}")
def multi_msg(self, level: str, msg: any):
if isinstance(msg, (str, int, float, bool)):
self.massage(f"{level.upper()}::{msg}")
elif isinstance(msg, (tuple, list, set)):
for _msg in msg:
self.multi_msg(level, _msg)
elif isinstance(msg, dict):
for _msg_key in msg:
Ну собственно самописный логгер, потому что "библиатечный логгер переусложнен НИНАДА!"