• python ColourLog


      1 #!/usr/bin/env python3
      2 # _*_ coding:utf-8
      3 import time
      4 from termcolor import cprint
      5 import sys
      6 import os
      7 from parameters import Parameters
      8 
      9 class Singleton(object):
     10     def __new__(cls, *args, **kwargs):
     11         if not hasattr(cls, '_the_instance'):
     12             cls._the_instance = object.__new__(cls)
     13         return cls._the_instance
     14 
     15 
     16 class ColourInfo(Singleton):
     17 
     18     def __init__(self, filename, mode='a', steam=None, encoding=None, delay=False, count=2):
     19         self.filename = os.fspath(filename)
     20         self.baseFilename = os.path.abspath(filename)
     21         self.mode = mode
     22         self.encoding = encoding
     23         self.delay = delay
     24         if steam is None:
     25             self.steam = sys.stderr
     26         self.steam = steam
     27         self.__console__ = sys.stdout
     28         self.count = count
     29 
     30     @staticmethod
     31     def colour(msg, colour):
     32         info = lambda x: cprint(x, colour)
     33         return info(msg)
     34 
     35     def show_message(self, level=None, msg=None):
     36         if level == 'debug':
     37             self.colour(msg, 'blue')
     38         elif level == 'info':
     39             self.colour(msg, 'green')
     40         elif level == 'error':
     41             self.colour(msg, 'red')
     42         elif level == 'warn':
     43             self.colour(msg, 'yellow')
     44         elif level == 'success':
     45             self.colour(msg, 'cyan')
     46 
     47     def redirected_output(self, level, msg):
     48         for sign in range(1, self.count):
     49             # Record the current output pointing to the console by default
     50             temp = self.__console__
     51             if self.delay:
     52                 self.steam = None
     53             else:
     54                 with open(self.filename, self.mode, encoding=self.encoding) as file:
     55                     # Output to TXT file.
     56                     sys.stdout = file
     57                     self.show_message(level, msg)
     58                 # The output is redirected back to the console.
     59                 sys.stdout = temp
     60                 self.show_message(level, msg)
     61 
     62 class Logger(object):
     63 
     64     def __init__(self):
     65         self.log_name = Parameters().log_name()
     66 
     67     @property
     68     def __console__(self):
     69         return ColourInfo(self.log_name)
     70 
     71     @staticmethod
     72     def get_today():
     73         return time.strftime('%Y-%m-%d', time.localtime(time.time()))
     74 
     75     @staticmethod
     76     def get_now_time():
     77         return time.strftime('%Y-%m-%d-%H_%M_%S', time.localtime(time.time()))
     78 
     79     def info(self, msg):
     80         """
     81         Normal log output
     82         :param msg:         log message str type
     83 
     84         Usage:
     85                     info('message')
     86         """
     87         self.__console__.redirected_output('info', self.get_now_time() + ' [INFO] ' + "".join(msg))
     88 
     89     def debug(self, msg):
     90         """
     91         Debug log output
     92         :param msg:         log message str type
     93 
     94         Usage:
     95                     debug('message')
     96         """
     97         self.__console__.redirected_output('debug', self.get_now_time() + ' [DEBUG] ' + "".join(msg))
     98 
     99     def error(self, msg):
    100         """
    101         error log output
    102         :param msg:         log message str type
    103 
    104         Usage:
    105                     error('message')
    106         """
    107         self.__console__.redirected_output('error', self.get_now_time() + ' [ERROR] ' + "".join(msg))
    108 
    109     def warn(self, msg):
    110         """
    111         warn log output
    112         :param msg:         log messages str type
    113 
    114         Usage:
    115                     warn('message')
    116         """
    117         self.__console__.redirected_output('warn', self.get_now_time() + ' [WARN] ' + "".join(msg))
    118 
    119     def success(self, msg):
    120         """
    121         success log output
    122         :param msg:         log message str type
    123 
    124         Usage:
    125                     success('message')
    126         """
    127         self.__console__.redirected_output('success', self.get_now_time() + ' [SUCCESS] ' + "".join(msg))
    128 
    129 
    130 if __name__ == '__main__':
    131     log = Logger()
    132     log.info('1')
    133     log.error('2')
    134     log.warn('3')
    135     log.success('4')
    136     log.debug('5')

    Note:parameters  module 为本人项目中的项目参数模块,log path 根据自己实际项目路径参数自己定义。termcolor module  pip  install  不解释了。。。

  • 相关阅读:
    HDOJ 2577 How To Type
    HDOJ 1171 Big Event in HDU
    HDOJ 2159 FATE
    HDOJ 1176 免费馅饼
    POJ 1014 Dividing
    HDOJ 2844 Coins
    可以设置DefaultButton的TextBox控件
    setTimeout和setInterval的使用
    C# 调用ExchangeWebservice的相关代码
    实现IConfigurationSectionHandler接口来编写自定义配置
  • 原文地址:https://www.cnblogs.com/xiaoxiaolulu/p/8602875.html
Copyright © 2020-2023  润新知