Browse Source

Initial commit

Lertsenem 5 years ago
commit
f2aff89801
1 changed files with 82 additions and 0 deletions
  1. 82 0
      __init__.py

+ 82 - 0
__init__.py

@@ -0,0 +1,82 @@
1
+#!/usr/bin/env python3
2
+# encoding: utf8
3
+
4
+import logging
5
+
6
+class ColoredFormatter(logging.Formatter):
7
+
8
+    FG_BLACK   = 30
9
+    FG_RED     = 31
10
+    FG_GREEN   = 32
11
+    FG_YELLOW  = 33
12
+    FG_BLUE    = 34
13
+    FG_MAGENTA = 35
14
+    FG_CYAN    = 36
15
+    FG_WHITE   = 37
16
+    BG_BLACK   = 40
17
+    BG_RED     = 41
18
+    BG_GREEN   = 42
19
+    BG_YELLOW  = 43
20
+    BG_BLUE    = 44
21
+    BG_MAGENTA = 45
22
+    BG_CYAN    = 46
23
+    BG_WHITE   = 47
24
+    BLACK      = FG_BLACK
25
+    RED        = FG_RED
26
+    GREEN      = FG_GREEN
27
+    YELLOW     = FG_YELLOW
28
+    BLUE       = FG_BLUE
29
+    MAGENTA    = FG_MAGENTA
30
+    CYAN       = FG_CYAN
31
+    WHITE      = FG_WHITE
32
+
33
+    # These are the sequences need to get colored ouput
34
+    RESET_SEQ = "\033[0m"
35
+    COLOR_SEQ = "\033[{:d}m"
36
+    BOLD_SEQ  = "\033[1m"
37
+
38
+    # -------------------------------------------------------------------------
39
+    def __init__( self,
40
+                  fmt=None,
41
+                  datefmt=None,
42
+                  style='%',
43
+                  colors={ 'WARNING' : YELLOW,
44
+                           'DEBUG'   : BLUE,
45
+                           'CRITICAL': BG_RED,
46
+                           'ERROR'   : RED,    } ):
47
+
48
+        super(ColoredFormatter, self).__init__(fmt, datefmt, style)
49
+
50
+        self.colors = colors
51
+
52
+    # -------------------------------------------------------------------------
53
+    def format(self, record):
54
+
55
+        levelname = record.levelname
56
+
57
+        if levelname in self.colors:
58
+            return (   self.COLOR_SEQ.format(self.colors[levelname]) \
59
+                     + super(ColoredFormatter, self).format(record)  \
60
+                     + self.RESET_SEQ  )
61
+
62
+        return super(ColoredFormatter, self).format(record)  \
63
+
64
+
65
+# =============================================================================
66
+if __name__ == '__main__':
67
+    log = logging.getLogger("test")
68
+    log.setLevel(logging.DEBUG)
69
+
70
+    log_handler= logging.StreamHandler()
71
+    
72
+    log_formatter = ColoredFormatter("%(asctime)s: %(message)s")
73
+
74
+    log_handler.setFormatter(log_formatter)
75
+
76
+    log.addHandler(log_handler)
77
+
78
+    log.debug("This is a debug log")
79
+    log.info("This is an info log")
80
+    log.warning("This is warning log")
81
+    log.error("This is an error log")
82
+    log.critical("This is critical log")