Aestate
Log.py
Go to the documentation of this file.
1 import datetime
2 import os
3 import sys
4 import threading
5 import traceback
6 
7 from aestate.util.others import write, logTupleToText
8 from aestate.work.Cache import LogCache
9 from aestate.work.Modes import Singleton
10 from aestate.exception import LogStatus
11 from aestate.util import others
12 from aestate.work.commad import __log_logo__
13 
14 
16  DATETIME_FORMAT = 27
17  INFO_FORMAT = 5
18  LINE_FORMAT = 5
19  OPERATION_FORMAT = 14
20  # HEX_FORMAT = 17
21  TASK_FORMAT = 7
22  # CLASS_FORMAT = 70
23  MSG_FORMAT = 0
24 
25 
27  """
28  控制台类型
29  """
30 
31  class FontColor:
32  # 黑色
33  BLACK = 30
34  # 灰色
35  GRAY = 90
36  # 粉色
37  PINK = 31
38  # 红色
39  RED = 35
40  # 绿色
41  GREEN = 32
42  # 浅绿色
43  LIGHT_GREEN = 91
44  # 黄色
45  YELLOW = 33
46  # 浅黄色
47  LIGHT_YELLOW = 92
48  # 深黄色
49  DARK_YELLOW = 93
50  # 紫色
51  PURPLE = 34
52  # 浅紫色
53  LIGHT_PURPLE = 96
54  # 青蓝色
55  CYAN = 36
56  # 白色
57  WHITE = 37
58  # 成功的颜色 和 info的颜色
59  SUCCESS_COLOR = GREEN
60  # 失败的颜色 和 错误的颜色
61  ERROR_COLOR = RED
62  # 警告的颜色
63  WARNING_COLOR = YELLOW
64 
66  # 黑色
67  BLACK = 40
68  # 红色
69  RED = 41
70  # 绿色
71  GREEN = 42
72  # 黄色
73  YELLOW = 43
74  # 蓝色
75  BLUE = 44
76  # 紫红色
77  FUCHSIA = 45
78  # 青蓝色
79  CYAN = 46
80  # 白色
81  WHITE = 47
82 
83  class ShowType:
84  # 默认
85  DEFAULT = 0
86  # 高亮
87  HIGHLIGHT = 1
88  # 下划线
89  UNDERSCORE = 4
90  # 闪烁
91  FLASHING = 5
92  # 反显
93  REVERSE = 7
94  # 不可见
95  INVISIBLE = 8
96 
97 
99  def __init__(self):
100  self.fontColor = ConsoleColor.FontColor.GREEN
101  self.showType = ConsoleColor.ShowType.DEFAULT
102  self.backColor = None
103 
104  # @staticmethod
105  # def write(messages, consoleWriteObj=None):
106  # prefix = "{};".format(consoleWriteObj.showType) if consoleWriteObj.showType is not None else ""
107  # center = ";".format(consoleWriteObj.backColor) if consoleWriteObj.backColor is not None else ""
108  # suffix = "{}m{}".format(consoleWriteObj.fontColor, messages)
109  # out = "\033[{}{}{}\033[0m".format(prefix, center, suffix)
110  # print(out)
111 
112  @staticmethod
113  def format_color(text, color=None):
114  if color is not None:
115  prefix = "{};".format(ConsoleColor.ShowType.DEFAULT)
116  suffix = "{}m{}".format(color, text)
117  out = "\033[{};{}\033[0m".format(prefix, suffix)
118  return out
119  return text
120 
121 
122 class ALog(object):
123  _instance_lock = threading.RLock()
124 
125  def __init__(self, path, print_flag=False, save_flag=False, max_clear=10):
126  """
127 
128  初始化配置
129 
130  :param path:保存的路径
131 
132  :param print_flag:是否打印日志 默认False
133 
134  :param save_flag:是否保存日志 默认False
135 
136  :param max_clear:日志储存最大限制,默认10MB 单位:MB
137 
138  """
139  self.max_clear = max_clear * 1024 * 1000
140  self.path = path
141  self.print_flag = print_flag
142  self.save_flag = save_flag
143 
144  @staticmethod
145  def pure_log(msg, **kwargs):
146  """
147  输出任务执行日志
148 
149  :param msg:消息
150 
151  """
152  ALog.log(msg=msg, **kwargs)
153 
154  @staticmethod
155  def format_text(field: LogStatus, line, obj, task_name, msg, ned_text=False,
156  text_color: ConsoleColor.FontColor = None):
157  """
158  将字符串格式化成好看的颜色
159  """
160  try:
161  if obj is not None:
162  write_repr = others.fullname(obj)
163  else:
164  write_repr = 'OBJECT IS NULL'
165  except TypeError:
166  write_repr = 'OBJECT CAN`T NOT PARSE'
167  t = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')
168  pure_text = ' '.join([str(t), str(field.value), str(line), str(hex(id(obj))),
169  '[{}]'.format(task_name), str(write_repr), f" : {msg}"])
170  t = ConsoleWrite.format_color(f"{t}".ljust(FieldsLength.DATETIME_FORMAT), ConsoleColor.FontColor.CYAN)
171  _field = ConsoleWrite.format_color(f"{field.value}".rjust(FieldsLength.INFO_FORMAT),
172  ConsoleColor.FontColor.GREEN
173  if field == LogStatus.Info
174  else ConsoleColor.FontColor.RED
175  if field == LogStatus.Error
176  else ConsoleColor.FontColor.YELLOW
177  if field == LogStatus.Warn
178  else ConsoleColor.FontColor.YELLOW)
179  line = f"{line}".rjust(FieldsLength.LINE_FORMAT)
180  hex_id = ConsoleWrite.format_color(f" {str(hex(id(obj)))}", ConsoleColor.FontColor.PINK)
181  task_name = ConsoleWrite.format_color(f"{task_name}".rjust(FieldsLength.TASK_FORMAT),
182  ConsoleColor.FontColor.PURPLE)
183  write_repr = ConsoleWrite.format_color(write_repr,
184  ConsoleColor.FontColor.LIGHT_GREEN
185  if field != LogStatus.Error
186  else ConsoleColor.FontColor.RED)
187  msg = ConsoleWrite.format_color(f" : {msg}", text_color)
188  info = "{}{}{}{}{}{}{}".format(t, _field, line, hex_id, ' [{}] '.format(task_name), write_repr, msg)
189  if ned_text:
190  return info, pure_text
191  return info
192 
193  @staticmethod
194  def log(msg, obj=None, line=sys._getframe().f_back.f_lineno, task_name='TEXT', LogObject=None,
195  field: LogStatus = LogStatus.Info, func=None,
196  text_color: ConsoleColor.FontColor = None, **kwargs):
197  """
198  输出任务执行日志
199 
200  :param msg:消息
201  :param obj:执行日志的对象地址
202  :param line:被调用前的行数
203  :param task_name:任务对象的值
204  :param LogObject:写出文件的对象
205  :param field:日志模式
206  :param func:日志执行后的自定义操作
207  """
208 
209  try:
210  if obj is not None:
211  write_repr = others.fullname(obj)
212  else:
213  write_repr = 'OBJECT IS NULL'
214  except TypeError:
215  write_repr = 'OBJECT CAN`T NOT PARSE'
216 
217  # write_repr = repr if repr and not repr_c else repr_c[0] if repr_c else type(obj)
218  # 格式:时间 类型 被调用时行数 对象地址 日志信息 执行类 信息
219  t = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
220  con_text = ' '.join([str(t), str(field.value), str(line), str(hex(id(obj))),
221  '[{}]'.format(task_name), str(write_repr), f" : {msg}"])
222  info = ALog.format_text(field, line, obj, task_name, msg, text_color=text_color)
223 
224  # print(info)
225 
226  def __log_obj_write__(_object):
227  if _object is not None:
228  if field == LogStatus.Info:
229  _object.info(con_text, pure_text=info)
230  elif field == LogStatus.Error:
231  _object.error(con_text, pure_text=info)
232  elif field == LogStatus.Warn:
233  _object.warn(con_text, pure_text=info)
234  else:
235  _object.info(con_text, pure_text=info)
236 
237  if obj is not None:
238  if hasattr(obj, 'log_obj'):
239  __log_obj_write__(obj.log_obj)
240  else:
241  __log_obj_write__(LogObject)
242  else:
243  __log_obj_write__(LogObject)
244  if func is not None:
245  func(con_text)
246 
247  return info
248 
249  @staticmethod
250  def warning(**kwargs):
251  ALog.log(task_name='WARNING', field=LogStatus.Warn, **kwargs)
252 
253  @staticmethod
254  def log_error(msg, obj=None, line=sys._getframe().f_back.f_lineno, task_name='ERROR',
255  LogObject=None, raise_exception=False):
256  """
257  :param msg:描述
258  :param line:行
259  :param obj:执行的对象,当允许抛出异常时,则指明该对象为一个Exception或他的子类
260  :param task_name:线程唯一名称
261  :param LogObject:日志对象
262  :param raise_exception:是否抛出异常
263  """
264  text = [msg]
265 
266  def get_stack():
267  text.append('\n')
268  exc_type, exc_value, exc_traceback_obj = sys.exc_info()
269  extracted_list = traceback.extract_tb(exc_traceback_obj)
270  for item in traceback.StackSummary.from_list(extracted_list).format():
271  text.append(item)
272 
273  if raise_exception:
274  if isinstance(obj, type):
275  try:
276  raise obj(msg)
277  except obj:
278  get_stack()
279  text.append(f'{obj.__name__} :{msg}')
280  else:
281  get_stack()
282  text.append(f'{obj.__class__.__name__} :{msg}')
283  ALog.log(msg=''.join(text), obj=obj, line=line, task_name=task_name,
284  LogObject=LogObject if LogObject is not None else None, field=LogStatus.Error,
285  text_color=ConsoleColor.FontColor.RED)
286 
287  def template(self, status: LogStatus, *content, **kwargs):
288  log_cache = LogCache()
289  _path = log_cache.get_filename(self.path, self.max_clear, status)
290  if status == LogStatus.Info:
291  logo_show = 'info_logo_show'
292  elif status == LogStatus.Warn:
293  logo_show = 'warn_logo_show'
294  elif status == LogStatus.Error:
295  logo_show = 'error_logo_show'
296  else:
297  logo_show = 'info_logo_show'
298 
299  ls = getattr(log_cache, logo_show)
300  if not ls:
301  setattr(log_cache, logo_show, True)
302  self.log_util(_path, __log_logo__)
303  self.log_util(_path, *content)
304  text = kwargs['pure_text'] \
305  if 'pure_text' in kwargs.keys() else ALog.format_text(status, sys._getframe().f_back.f_lineno, self,
306  status.value, logTupleToText(False, *content))
307  print(text)
308 
309  def info(self, *content, **kwargs):
310  """
311  成功日志
312  :param content:内容
313  :return:
314  """
315  # _path = self.get_filename(e_LogStatus.Info)
316  # _path = LogCache().get_filename(self.path, self.max_clear, e_LogStatus.Info)
317  # if not self.__info_logo_show__:
318  # self.__info_logo_show__ = True
319  # self.log_util(_path, __log_logo__)
320  # self.log_util(_path, *content)
321  # text = kwargs['pure_text'] \
322  # if 'pure_text' in kwargs.keys() else ALog.format_text(
323  # e_LogStatus.Info, sys._getframe().f_back.f_lineno, self,
324  # e_LogStatus.Info.value,
325  # logTupleToText(False, *content)
326  # )
327  # print(text)
328  self.template(LogStatus.Info, *content, **kwargs)
329 
330  def warn(self, *content, **kwargs):
331  """
332  警告日志
333  :param content:内容
334  :return:
335  """
336  self.template(LogStatus.Warn, *content, **kwargs)
337 
338  def error(self, *content, **kwargs):
339  """
340  错误日志
341  :param content:内容
342  :return:
343  """
344  self.template(LogStatus.Error, *content, **kwargs)
345 
346  def log_util(self, path_str, *content):
347  """
348  日志工具
349  :param path_str:
350  :param content:
351  :return:
352  """
353  path = self.get_path(path_str)
354  if self.save_flag:
355  write(path, *content)
356 
357  def get_path(self, end_path):
358  """
359  日志类获取绝对路径
360  :param end_path:
361  :return:
362  """
363  _STATIC_TXT = os.path.join('', self.path + end_path)
364  return _STATIC_TXT
365 
366  def __new__(cls, *args, **kwargs):
367  instance = Singleton.createObject(cls)
368  return instance
369 
370 
371 class logging(object):
372 
373  @classmethod
374  def gen(cls, _object) -> ALog:
375  return _object.log_obj
aestate.util.Log.ALog.warn
def warn(self, *content, **kwargs)
Definition: Log.py:330
aestate.util.Log.ALog.max_clear
max_clear
Definition: Log.py:139
aestate.work.commad
Definition: commad.py:1
aestate.util.Log.ALog.warning
def warning(**kwargs)
Definition: Log.py:250
aestate.util.Log.ALog.log_util
def log_util(self, path_str, *content)
Definition: Log.py:346
aestate.work.Cache.LogCache
Definition: Cache.py:104
aestate.util.Log.ALog.template
def template(self, LogStatus status, *content, **kwargs)
Definition: Log.py:287
aestate.util.Log.ALog.__init__
def __init__(self, path, print_flag=False, save_flag=False, max_clear=10)
Definition: Log.py:125
aestate.util.Log.ALog.log
def log(msg, obj=None, line=sys._getframe().f_back.f_lineno, task_name='TEXT', LogObject=None, LogStatus field=LogStatus.Info, func=None, ConsoleColor.FontColor text_color=None, **kwargs)
Definition: Log.py:194
aestate.util.Log.logging
Definition: Log.py:371
aestate.util.Log.ConsoleWrite.fontColor
fontColor
Definition: Log.py:100
aestate.util.Log.ConsoleWrite.__init__
def __init__(self)
Definition: Log.py:99
aestate.util.Log.ALog.print_flag
print_flag
Definition: Log.py:141
aestate.util.others
Definition: others.py:1
aestate.util.Log.ALog.pure_log
def pure_log(msg, **kwargs)
Definition: Log.py:145
aestate.util.Log.ConsoleColor.ShowType
Definition: Log.py:83
aestate.util.Log.ALog.error
def error(self, *content, **kwargs)
Definition: Log.py:338
aestate.util.Log.ALog.__new__
def __new__(cls, *args, **kwargs)
Definition: Log.py:366
aestate.work.Cache
Definition: Cache.py:1
aestate.util.Log.ALog.path
path
Definition: Log.py:140
aestate.util.Log.ConsoleColor.FontColor
Definition: Log.py:31
aestate.util.Log.ALog.get_path
def get_path(self, end_path)
Definition: Log.py:357
aestate.util
Definition: __init__.py:1
aestate.util.Log.ConsoleWrite.backColor
backColor
Definition: Log.py:102
aestate.util.Log.ConsoleWrite.showType
showType
Definition: Log.py:101
aestate.work.Modes
Definition: Modes.py:1
aestate.exception
Definition: __init__.py:1
aestate.util.Log.ConsoleWrite
Definition: Log.py:98
aestate.util.Log.ConsoleWrite.format_color
def format_color(text, color=None)
Definition: Log.py:113
aestate.util.Log.ConsoleColor.BackgroundColor
Definition: Log.py:65
aestate.util.Log.ALog.format_text
def format_text(LogStatus field, line, obj, task_name, msg, ned_text=False, ConsoleColor.FontColor text_color=None)
Definition: Log.py:155
aestate.util.Log.FieldsLength
Definition: Log.py:15
aestate.util.Log.ConsoleColor
Definition: Log.py:26
aestate.util.others.logTupleToText
def logTupleToText(next_line=True, *content)
Definition: others.py:65
aestate.util.Log.logging.gen
ALog gen(cls, _object)
Definition: Log.py:374
aestate.util.Log.ALog.log_error
def log_error(msg, obj=None, line=sys._getframe().f_back.f_lineno, task_name='ERROR', LogObject=None, raise_exception=False)
Definition: Log.py:254
aestate.util.others.write
def write(path, *content)
Definition: others.py:82
aestate.util.Log.ALog.info
def info(self, *content, **kwargs)
Definition: Log.py:309
aestate.util.Log.ALog.save_flag
save_flag
Definition: Log.py:142
aestate.util.Log.ALog
Definition: Log.py:122