Statistics
| Branch: | Tag: | Revision:

root / qa / qa_logging.py @ bfca72bc

History | View | Annotate | Download (1.8 kB)

1
#
2
#
3

    
4
# Copyright (C) 2014 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21
""" Handles the logging of messages with appropriate coloring.
22

23
"""
24

    
25
import sys
26

    
27

    
28
_INFO_SEQ = None
29
_WARNING_SEQ = None
30
_ERROR_SEQ = None
31
_RESET_SEQ = None
32

    
33

    
34
def _SetupColours():
35
  """Initializes the colour constants.
36

37
  """
38
  # pylint: disable=W0603
39
  # due to global usage
40
  global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ
41

    
42
  # Don't use colours if stdout isn't a terminal
43
  if not sys.stdout.isatty():
44
    return
45

    
46
  try:
47
    import curses
48
  except ImportError:
49
    # Don't use colours if curses module can't be imported
50
    return
51

    
52
  curses.setupterm()
53

    
54
  _RESET_SEQ = curses.tigetstr("op")
55

    
56
  setaf = curses.tigetstr("setaf")
57
  _INFO_SEQ = curses.tparm(setaf, curses.COLOR_GREEN)
58
  _WARNING_SEQ = curses.tparm(setaf, curses.COLOR_YELLOW)
59
  _ERROR_SEQ = curses.tparm(setaf, curses.COLOR_RED)
60

    
61

    
62
_SetupColours()
63

    
64

    
65
def _FormatWithColor(text, seq):
66
  if not seq:
67
    return text
68
  return "%s%s%s" % (seq, text, _RESET_SEQ)
69

    
70

    
71
FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
72
FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
73
FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)