转载请注明:

 

 

通常我们在构建 python 系统时,往往需要一个简单的 logging 框架。python 自带的 logging 框架的确十分完善,但是本身过于复杂,因此需要自行封装来满足我们的高(zhuang)端(b)需求

1. 常用的格式化字符串:

       这是我比较常用的格式化字符串,不同的人可能有不同的习惯

1 # 第一种,月日年的输出
2 DEFAULT_DATE_FMT = '%a, %p %b %d %Y %H:%M:%S'
3 # Wed, Sep 27 2017 18:56:40
4 
5 #第二种,年月日
6 DEFAULT_DATE_FMT = '%Y-%m-%d %a, %p %H:%M:%S'
7 # Wed, 2017-09-27 18:59:33

 

2. logging 框架的简单基本用法:

1 # 简单的logging配置
2 import logging
3 
4 logging.basicConfig(level=logging.DEBUG,
5                 format='[%(asctime)s %(filename)s [line:%(lineno)d]] %(levelname)s %(message)s',
6                 datefmt='%a, %d %b %Y %H:%M:%S',
7                 filename='myapp.log',
8                 filemode='w')

这样的好处是,在一些情况下可以简单配置log之后输出,但是其格式中的样式是难以变化的

 

3. 封装自己的 logger 框架

毫无疑问,为了方便代码的维护和重构,职责单一原则必不可少。目前的 v0.1 版本的 UML 图如下:

python 简单日志框架 自定义logger

 

 

3.1 颜色:

 CmdColor 类主要用于存储命令行控制台的字体转义字符串,并且保证颜色名称到颜色转义字符串的映射,其中包括一些常用的颜色

其中代码如下:

本类作为颜色的映射,主要实现了获取所有颜色,以及查重的set,以及名称到字符串的映射

 1 class CmdColor():
 2     ''' Cmd color escape strings '''
 3     # color escape strings
 4     __COLOR_RED    = '\033[1;31m'
 5     __COLOR_GREEN  = '\033[1;32m'
 6     __COLOR_YELLOW = '\033[1;33m'
 7     __COLOR_BLUE   = '\033[1;34m'
 8     __COLOR_PURPLE = '\033[1;35m'
 9     __COLOR_CYAN   = '\033[1;36m'
10     __COLOR_GRAY   = '\033[1;37m'
11     __COLOR_WHITE  = '\033[1;38m'
12     __COLOR_RESET  = '\033[1;0m'
13 
14     # color names to escape strings
15     __COLOR_2_STR = {
16         'red'   : __COLOR_RED,
17         'green' : __COLOR_GREEN,
18         'yellow': __COLOR_YELLOW,
19         'blue'  : __COLOR_BLUE,
20         'purple': __COLOR_PURPLE,
21         'cyan'  : __COLOR_CYAN,
22         'gray'  : __COLOR_GRAY,
23         'white' : __COLOR_WHITE,
24         'reset' : __COLOR_RESET,
25     }
26 
27     __COLORS = __COLOR_2_STR.keys()
28     __COLOR_SET = set(__COLORS)
29 
30     @classmethod
31     def get_color_by_str(cls, color_str):
32         if not isinstance(color_str, str):
33             raise TypeError("color string must str, but type: '%s' passed in." % type(color_str))
34         color = color_str.lower()
35         if color not in cls.__COLOR_SET:
36             raise ValueError("no such color: '%s'" % color)
37         return cls.__COLOR_2_STR[color]
38 
39     @classmethod
40     def get_all_colors(cls):
41         ''' return a list that contains all the color names '''
42         return cls.__COLORS
43 
44     @classmethod
45     def get_color_set(cls):
46         ''' return a set contains the name of all the colors'''
47         return cls.__COLOR_SET
CmdColor类

相关文章:

  • 2021-09-05
  • 2021-09-24
  • 2022-01-11
  • 2021-12-26
  • 2021-11-15
  • 2022-01-26
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2020-10-13
  • 2021-12-23
  • 2021-12-27
  • 2022-01-20
相关资源
相似解决方案