smbclientng.core.Logger

  1#!/usr/bin/env python3
  2# -*- coding: utf-8 -*-
  3# File name          : LocalFileIO.py
  4# Author             : Podalirius (@podalirius_)
  5# Date created       : 24 June 2024
  6
  7
  8import os
  9import re
 10from enum import Enum
 11
 12
 13class LogLevel(Enum):
 14    INFO = 1
 15    DEBUG = 2
 16    WARNING = 3
 17    ERROR = 4
 18    CRITICAL = 5
 19
 20
 21class Logger(object):
 22    """
 23    A Logger class that provides logging functionalities with various levels such as INFO, DEBUG, WARNING, ERROR, and CRITICAL.
 24    It supports color-coded output, which can be disabled, and can also log messages to a file.
 25
 26    Attributes:
 27        __debug (bool): If True, debug level messages will be printed and logged.
 28        __nocolors (bool): If True, disables color-coded output.
 29        logfile (str|None): Path to a file where logs will be written. If None, logging to a file is disabled.
 30
 31    Methods:
 32        __init__(debug=False, logfile=None, nocolors=False): Initializes the Logger instance.
 33        print(message=""): Prints a message to stdout and logs it to a file if logging is enabled.
 34        info(message): Logs a message at the INFO level.
 35        debug(message): Logs a message at the DEBUG level if debugging is enabled.
 36        error(message): Logs a message at the ERROR level.
 37    """
 38
 39    def __init__(self, config, logfile=None):
 40        super(Logger, self).__init__()
 41        self.config = config
 42        self.logfile = logfile
 43        #
 44        if self.logfile is not None:
 45            if os.path.exists(self.logfile):
 46                k = 1
 47                while os.path.exists(self.logfile+(".%d"%k)):
 48                    k += 1
 49                self.logfile = self.logfile + (".%d" % k)
 50            open(self.logfile, "w").close()
 51
 52    def print(self, message="", end='\n'):
 53        """
 54        Prints a message to stdout and logs it to a file if logging is enabled.
 55
 56        This method prints the provided message to the standard output and also logs it to a file if a log file path is specified during the Logger instance initialization. The message can include color codes for color-coded output, which can be disabled by setting the `nocolors` attribute to True.
 57
 58        Args:
 59            message (str): The message to be printed and logged.
 60        """
 61
 62        nocolor_message = re.sub(r"\x1b[\[]([0-9;]+)m", "", message)
 63        if self.config.no_colors:
 64            print(nocolor_message, end=end)
 65        else:
 66            print(message, end=end)
 67        self.__write_to_logfile(nocolor_message, end=end)
 68
 69    def info(self, message):
 70        """
 71        Logs a message at the INFO level.
 72
 73        This method logs the provided message at the INFO level. The message can include color codes for color-coded output, which can be disabled by setting the `nocolors` attribute to True. The message is also logged to a file if a log file path is specified during the Logger instance initialization.
 74
 75        Args:
 76            message (str): The message to be logged at the INFO level.
 77        """
 78
 79        nocolor_message = re.sub(r"\x1b[\[]([0-9;]+)m", "", message)
 80        if self.config.no_colors:
 81            print("[info] %s" % nocolor_message)
 82        else:
 83            print("[\x1b[1;92minfo\x1b[0m] %s" % message)
 84        self.__write_to_logfile("[info] %s" % nocolor_message)
 85
 86    def debug(self, message):
 87        """
 88        Logs a message at the DEBUG level if debugging is enabled.
 89
 90        This method logs the provided message at the DEBUG level if the `debug` attribute is set to True during the Logger instance initialization. The message can include color codes for color-coded output, which can be disabled by setting the `nocolors` attribute to True.
 91
 92        Args:
 93            message (str): The message to be logged.
 94        """
 95        
 96        if self.config.debug == True:
 97            nocolor_message = re.sub(r"\x1b[\[]([0-9;]+)m", "", message)
 98            if self.config.no_colors:
 99                print("[debug] %s" % nocolor_message)
100            else:
101                print("[debug] %s" % message)
102            self.__write_to_logfile("[debug] %s" % nocolor_message)
103
104    def error(self, message):
105        """
106        Logs an error message to the console and the log file.
107
108        This method logs the provided error message to the standard error output and also logs it to a file if a log file path is specified during the Logger instance initialization. The message can include color codes for color-coded output, which can be disabled by setting the `nocolors` attribute to True.
109
110        Args:
111            message (str): The error message to be logged.
112        """
113
114        nocolor_message = re.sub(r"\x1b[\[]([0-9;]+)m", "", message)
115        if self.config.no_colors:
116            print("[error] %s" % nocolor_message)
117        else:
118            print("[\x1b[1;91merror\x1b[0m] %s" % message)
119        self.__write_to_logfile("[error] %s" % nocolor_message)
120
121    def __write_to_logfile(self, message, end='\n'):
122        """
123        Writes the provided message to the log file specified during Logger instance initialization.
124
125        This method appends the provided message to the log file specified by the `logfile` attribute. If no log file path is specified, this method does nothing.
126
127        Args:
128            message (str): The message to be written to the log file.
129        """
130
131        if self.logfile is not None:
132            f = open(self.logfile, "a")
133            f.write(message + end)
134            f.close()
class LogLevel(enum.Enum):
14class LogLevel(Enum):
15    INFO = 1
16    DEBUG = 2
17    WARNING = 3
18    ERROR = 4
19    CRITICAL = 5

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
...     RED = 1
...     BLUE = 2
...     GREEN = 3

Access them by:

  • attribute access:

    >>> Color.RED
    <Color.RED: 1>
    
  • value lookup:

    >>> Color(1)
    <Color.RED: 1>
    
  • name lookup:

    >>> Color['RED']
    <Color.RED: 1>
    

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details.

INFO = <LogLevel.INFO: 1>
DEBUG = <LogLevel.DEBUG: 2>
WARNING = <LogLevel.WARNING: 3>
ERROR = <LogLevel.ERROR: 4>
CRITICAL = <LogLevel.CRITICAL: 5>
Inherited Members
enum.Enum
name
value
class Logger:
 22class Logger(object):
 23    """
 24    A Logger class that provides logging functionalities with various levels such as INFO, DEBUG, WARNING, ERROR, and CRITICAL.
 25    It supports color-coded output, which can be disabled, and can also log messages to a file.
 26
 27    Attributes:
 28        __debug (bool): If True, debug level messages will be printed and logged.
 29        __nocolors (bool): If True, disables color-coded output.
 30        logfile (str|None): Path to a file where logs will be written. If None, logging to a file is disabled.
 31
 32    Methods:
 33        __init__(debug=False, logfile=None, nocolors=False): Initializes the Logger instance.
 34        print(message=""): Prints a message to stdout and logs it to a file if logging is enabled.
 35        info(message): Logs a message at the INFO level.
 36        debug(message): Logs a message at the DEBUG level if debugging is enabled.
 37        error(message): Logs a message at the ERROR level.
 38    """
 39
 40    def __init__(self, config, logfile=None):
 41        super(Logger, self).__init__()
 42        self.config = config
 43        self.logfile = logfile
 44        #
 45        if self.logfile is not None:
 46            if os.path.exists(self.logfile):
 47                k = 1
 48                while os.path.exists(self.logfile+(".%d"%k)):
 49                    k += 1
 50                self.logfile = self.logfile + (".%d" % k)
 51            open(self.logfile, "w").close()
 52
 53    def print(self, message="", end='\n'):
 54        """
 55        Prints a message to stdout and logs it to a file if logging is enabled.
 56
 57        This method prints the provided message to the standard output and also logs it to a file if a log file path is specified during the Logger instance initialization. The message can include color codes for color-coded output, which can be disabled by setting the `nocolors` attribute to True.
 58
 59        Args:
 60            message (str): The message to be printed and logged.
 61        """
 62
 63        nocolor_message = re.sub(r"\x1b[\[]([0-9;]+)m", "", message)
 64        if self.config.no_colors:
 65            print(nocolor_message, end=end)
 66        else:
 67            print(message, end=end)
 68        self.__write_to_logfile(nocolor_message, end=end)
 69
 70    def info(self, message):
 71        """
 72        Logs a message at the INFO level.
 73
 74        This method logs the provided message at the INFO level. The message can include color codes for color-coded output, which can be disabled by setting the `nocolors` attribute to True. The message is also logged to a file if a log file path is specified during the Logger instance initialization.
 75
 76        Args:
 77            message (str): The message to be logged at the INFO level.
 78        """
 79
 80        nocolor_message = re.sub(r"\x1b[\[]([0-9;]+)m", "", message)
 81        if self.config.no_colors:
 82            print("[info] %s" % nocolor_message)
 83        else:
 84            print("[\x1b[1;92minfo\x1b[0m] %s" % message)
 85        self.__write_to_logfile("[info] %s" % nocolor_message)
 86
 87    def debug(self, message):
 88        """
 89        Logs a message at the DEBUG level if debugging is enabled.
 90
 91        This method logs the provided message at the DEBUG level if the `debug` attribute is set to True during the Logger instance initialization. The message can include color codes for color-coded output, which can be disabled by setting the `nocolors` attribute to True.
 92
 93        Args:
 94            message (str): The message to be logged.
 95        """
 96        
 97        if self.config.debug == True:
 98            nocolor_message = re.sub(r"\x1b[\[]([0-9;]+)m", "", message)
 99            if self.config.no_colors:
100                print("[debug] %s" % nocolor_message)
101            else:
102                print("[debug] %s" % message)
103            self.__write_to_logfile("[debug] %s" % nocolor_message)
104
105    def error(self, message):
106        """
107        Logs an error message to the console and the log file.
108
109        This method logs the provided error message to the standard error output and also logs it to a file if a log file path is specified during the Logger instance initialization. The message can include color codes for color-coded output, which can be disabled by setting the `nocolors` attribute to True.
110
111        Args:
112            message (str): The error message to be logged.
113        """
114
115        nocolor_message = re.sub(r"\x1b[\[]([0-9;]+)m", "", message)
116        if self.config.no_colors:
117            print("[error] %s" % nocolor_message)
118        else:
119            print("[\x1b[1;91merror\x1b[0m] %s" % message)
120        self.__write_to_logfile("[error] %s" % nocolor_message)
121
122    def __write_to_logfile(self, message, end='\n'):
123        """
124        Writes the provided message to the log file specified during Logger instance initialization.
125
126        This method appends the provided message to the log file specified by the `logfile` attribute. If no log file path is specified, this method does nothing.
127
128        Args:
129            message (str): The message to be written to the log file.
130        """
131
132        if self.logfile is not None:
133            f = open(self.logfile, "a")
134            f.write(message + end)
135            f.close()

A Logger class that provides logging functionalities with various levels such as INFO, DEBUG, WARNING, ERROR, and CRITICAL. It supports color-coded output, which can be disabled, and can also log messages to a file.

Attributes: __debug (bool): If True, debug level messages will be printed and logged. __nocolors (bool): If True, disables color-coded output. logfile (str|None): Path to a file where logs will be written. If None, logging to a file is disabled.

Methods: __init__(debug=False, logfile=None, nocolors=False): Initializes the Logger instance. print(message=""): Prints a message to stdout and logs it to a file if logging is enabled. info(message): Logs a message at the INFO level. debug(message): Logs a message at the DEBUG level if debugging is enabled. error(message): Logs a message at the ERROR level.

Logger(config, logfile=None)
40    def __init__(self, config, logfile=None):
41        super(Logger, self).__init__()
42        self.config = config
43        self.logfile = logfile
44        #
45        if self.logfile is not None:
46            if os.path.exists(self.logfile):
47                k = 1
48                while os.path.exists(self.logfile+(".%d"%k)):
49                    k += 1
50                self.logfile = self.logfile + (".%d" % k)
51            open(self.logfile, "w").close()
config
logfile
def print(self, message='', end='\n'):
53    def print(self, message="", end='\n'):
54        """
55        Prints a message to stdout and logs it to a file if logging is enabled.
56
57        This method prints the provided message to the standard output and also logs it to a file if a log file path is specified during the Logger instance initialization. The message can include color codes for color-coded output, which can be disabled by setting the `nocolors` attribute to True.
58
59        Args:
60            message (str): The message to be printed and logged.
61        """
62
63        nocolor_message = re.sub(r"\x1b[\[]([0-9;]+)m", "", message)
64        if self.config.no_colors:
65            print(nocolor_message, end=end)
66        else:
67            print(message, end=end)
68        self.__write_to_logfile(nocolor_message, end=end)

Prints a message to stdout and logs it to a file if logging is enabled.

This method prints the provided message to the standard output and also logs it to a file if a log file path is specified during the Logger instance initialization. The message can include color codes for color-coded output, which can be disabled by setting the nocolors attribute to True.

Args: message (str): The message to be printed and logged.

def info(self, message):
70    def info(self, message):
71        """
72        Logs a message at the INFO level.
73
74        This method logs the provided message at the INFO level. The message can include color codes for color-coded output, which can be disabled by setting the `nocolors` attribute to True. The message is also logged to a file if a log file path is specified during the Logger instance initialization.
75
76        Args:
77            message (str): The message to be logged at the INFO level.
78        """
79
80        nocolor_message = re.sub(r"\x1b[\[]([0-9;]+)m", "", message)
81        if self.config.no_colors:
82            print("[info] %s" % nocolor_message)
83        else:
84            print("[\x1b[1;92minfo\x1b[0m] %s" % message)
85        self.__write_to_logfile("[info] %s" % nocolor_message)

Logs a message at the INFO level.

This method logs the provided message at the INFO level. The message can include color codes for color-coded output, which can be disabled by setting the nocolors attribute to True. The message is also logged to a file if a log file path is specified during the Logger instance initialization.

Args: message (str): The message to be logged at the INFO level.

def debug(self, message):
 87    def debug(self, message):
 88        """
 89        Logs a message at the DEBUG level if debugging is enabled.
 90
 91        This method logs the provided message at the DEBUG level if the `debug` attribute is set to True during the Logger instance initialization. The message can include color codes for color-coded output, which can be disabled by setting the `nocolors` attribute to True.
 92
 93        Args:
 94            message (str): The message to be logged.
 95        """
 96        
 97        if self.config.debug == True:
 98            nocolor_message = re.sub(r"\x1b[\[]([0-9;]+)m", "", message)
 99            if self.config.no_colors:
100                print("[debug] %s" % nocolor_message)
101            else:
102                print("[debug] %s" % message)
103            self.__write_to_logfile("[debug] %s" % nocolor_message)

Logs a message at the DEBUG level if debugging is enabled.

This method logs the provided message at the DEBUG level if the debug attribute is set to True during the Logger instance initialization. The message can include color codes for color-coded output, which can be disabled by setting the nocolors attribute to True.

Args: message (str): The message to be logged.

def error(self, message):
105    def error(self, message):
106        """
107        Logs an error message to the console and the log file.
108
109        This method logs the provided error message to the standard error output and also logs it to a file if a log file path is specified during the Logger instance initialization. The message can include color codes for color-coded output, which can be disabled by setting the `nocolors` attribute to True.
110
111        Args:
112            message (str): The error message to be logged.
113        """
114
115        nocolor_message = re.sub(r"\x1b[\[]([0-9;]+)m", "", message)
116        if self.config.no_colors:
117            print("[error] %s" % nocolor_message)
118        else:
119            print("[\x1b[1;91merror\x1b[0m] %s" % message)
120        self.__write_to_logfile("[error] %s" % nocolor_message)

Logs an error message to the console and the log file.

This method logs the provided error message to the standard error output and also logs it to a file if a log file path is specified during the Logger instance initialization. The message can include color codes for color-coded output, which can be disabled by setting the nocolors attribute to True.

Args: message (str): The error message to be logged.