David Brazdil | 2c27f2c | 2015-05-12 18:06:38 +0100 | [diff] [blame] | 1 | # Copyright (C) 2014 The Android Open Source Project |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | from __future__ import print_function |
| 16 | import sys |
| 17 | |
| 18 | class Logger(object): |
| 19 | |
| 20 | class Level(object): |
| 21 | NoOutput, Error, Info = range(3) |
| 22 | |
| 23 | class Color(object): |
| 24 | Default, Blue, Gray, Purple, Red = range(5) |
| 25 | |
| 26 | @staticmethod |
| 27 | def terminalCode(color, out=sys.stdout): |
| 28 | if not out.isatty(): |
| 29 | return '' |
| 30 | elif color == Logger.Color.Blue: |
| 31 | return '\033[94m' |
| 32 | elif color == Logger.Color.Gray: |
| 33 | return '\033[37m' |
| 34 | elif color == Logger.Color.Purple: |
| 35 | return '\033[95m' |
| 36 | elif color == Logger.Color.Red: |
| 37 | return '\033[91m' |
| 38 | else: |
| 39 | return '\033[0m' |
| 40 | |
| 41 | Verbosity = Level.Info |
| 42 | |
| 43 | @staticmethod |
| 44 | def log(text, level=Level.Info, color=Color.Default, newLine=True, out=sys.stdout): |
| 45 | if level <= Logger.Verbosity: |
| 46 | text = Logger.Color.terminalCode(color, out) + text + \ |
| 47 | Logger.Color.terminalCode(Logger.Color.Default, out) |
| 48 | if newLine: |
| 49 | print(text, file=out) |
| 50 | else: |
| 51 | print(text, end="", file=out) |
| 52 | out.flush() |
| 53 | |
| 54 | @staticmethod |
| 55 | def fail(msg, file=None, line=-1): |
| 56 | location = "" |
| 57 | if file: |
| 58 | location += file + ":" |
| 59 | if line > 0: |
| 60 | location += str(line) + ":" |
| 61 | if location: |
| 62 | location += " " |
| 63 | |
| 64 | Logger.log(location, Logger.Level.Error, color=Logger.Color.Gray, newLine=False, out=sys.stderr) |
| 65 | Logger.log("error: ", Logger.Level.Error, color=Logger.Color.Red, newLine=False, out=sys.stderr) |
| 66 | Logger.log(msg, Logger.Level.Error, out=sys.stderr) |
| 67 | sys.exit(msg) |
| 68 | |
| 69 | @staticmethod |
| 70 | def startTest(name): |
| 71 | Logger.log("TEST ", color=Logger.Color.Purple, newLine=False) |
| 72 | Logger.log(name + "... ", newLine=False) |
| 73 | |
| 74 | @staticmethod |
| 75 | def testPassed(): |
| 76 | Logger.log("PASS", color=Logger.Color.Blue) |
| 77 | |
| 78 | @staticmethod |
| 79 | def testFailed(msg, file=None, line=-1): |
| 80 | Logger.log("FAIL", color=Logger.Color.Red) |
| 81 | Logger.fail(msg, file, line) |