ColorFormatter.py 1.13 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python
# -*- coding:utf-8 -*-

''' Custom logging color formatter

When logging, use the following format
[criticality] file - message
the color of [criticality] (warning, info, etc.) is different for each value

Adapted by ESA from examples found on StackOverflow
'''
Maxime Perrotin's avatar
Maxime Perrotin committed
12
13
14
15


import logging

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class ColorFormatter(logging.Formatter):
    ''' Custom color formatter for shell logging '''
    COLORS = {'WARNING'  : 33,  # yellow
              'INFO'     : 32,  # green
              'DEBUG'    : 37,  # white
              'CRITICAL' : 31,  # red
              'ERROR'    : 31}

    def __init__(self):
        ''' Create a custom format for the logging messages '''
        fmt = "[%(levelname)-19s] \033[1m%(filename)-20s\033[0m%(message)s"
        super(ColorFormatter, self).__init__(fmt)

    def format(self, record):
        ''' When formatting, set the color of the criticality level text '''
        col = self.COLORS[record.levelname]
        record.levelname = '\033[1m\033[{}m {}\033[0m'.format(col,
                                                              record.levelname)
        return super(ColorFormatter, self).format(record)