Logger.warn()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
1
# coding=utf-8
2
import os
3
import time
4
import sys
5
6
from colorama import Fore, Style
7
8
9
class Logger(object):
10
11
    def __init__(self):
12
13
        # Check if the logs directory exists and make it if it doesnt
14
        if not os.path.exists("logs"):
15
            os.mkdir("logs")
16
17
    def _getTimestamp(self):
18
        """Get a timestamp in the correct format"""
19
        return time.strftime("[%d/%m/%Y] %H:%M:%S")
20
21
    def _write(self, file, message):
22
        """Write a message to a file"""
23
        fh = open("logs/" + file, "a")
24
        fh.write(message + "\n")
25
        fh.flush()
26
        fh.close()
27
28
    def _print(self, message):
29
        """Output to stdout"""
30
        sys.stdout.write(message + "\n")
31
32
    def _err(self, message):
33
        """Output to stderr"""
34
        sys.stderr.write(message + "\n")
35
36
    # Logging levels
37
38
    def debug(self, message, toFile=True):
39
        """Log message with DEBUG warning level"""
40
        f_string = self._getTimestamp() + " | DEBUG | %s" % message
41
        if toFile:
42
            self._write("debug.log", f_string)
43
        self._print(self._getTimestamp() + " | " + Fore.CYAN + "DEBUG" + Style.RESET_ALL + " | %s" % message)
44
45
    def info(self, message, toFile=True):
46
        """Log message with INFO warning level"""
47
        f_string = self._getTimestamp() + " | INFO | %s" % message
48
        if toFile:
49
            self._write("info.log", f_string)
50
        self._print(self._getTimestamp() + " | " + Fore.GREEN + "INFO" + Style.RESET_ALL + " | %s" % message)
51
52
    def warn(self, message, toFile=True):
53
        """Log message with WARN warning level"""
54
        f_string = self._getTimestamp() + " | WARN | %s" % message
55
        if toFile:
56
            self._write("warn.log", f_string)
57
        self._print(self._getTimestamp() + " | " + Fore.YELLOW + "WARN" + Style.RESET_ALL + " | %s" % message)
58
59
    def error(self, message, toFile=True):
60
        """Log message with ERROR warning level"""
61
        f_string = self._getTimestamp() + " | ERROR | %s" % message
62
        if toFile:
63
            self._write("error.log", f_string)
64
        self._err(self._getTimestamp() + " | " + Fore.RED + "ERROR" + Style.RESET_ALL + " | %s" % message)
65
66
#Logger()