tradx 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tradx/logger/logger.py ADDED
@@ -0,0 +1,83 @@
1
+ import logging
2
+ import inspect
3
+ import os
4
+
5
+
6
+ class CustomLogger(logging.Logger):
7
+ """
8
+ CustomLogger is a subclass of logging.Logger that adds the ability to log messages with an additional 'caller' attribute.
9
+ Methods
10
+ -------
11
+ _log_with_caller(level, msg, *args, caller="Unknown", **kwargs)
12
+ Logs a message with the specified level and caller information.
13
+ info(msg, *args, caller="Unknown", **kwargs)
14
+ Logs a message with level INFO and caller information.
15
+ debug(msg, *args, caller="Unknown", **kwargs)
16
+ Logs a message with level DEBUG and caller information.
17
+ warning(msg, *args, caller="Unknown", **kwargs)
18
+ Logs a message with level WARNING and caller information.
19
+ error(msg, *args, caller="Unknown", **kwargs)
20
+ Logs a message with level ERROR and caller information.
21
+ critical(msg, *args, caller="Unknown", **kwargs)
22
+ Logs a message with level CRITICAL and caller information.
23
+ """
24
+
25
+
26
+ def _log_with_caller(self, level, msg, *args, caller="Unknown", **kwargs):
27
+ extra = kwargs.get("extra", {})
28
+ extra["caller"] = caller
29
+ kwargs["extra"] = extra
30
+ super().log(level, msg, *args, **kwargs)
31
+
32
+ def info(self, msg, *args, caller="Unknown", **kwargs):
33
+ self._log_with_caller(logging.INFO, msg, *args, caller=caller, **kwargs)
34
+
35
+ def debug(self, msg, *args, caller="Unknown", **kwargs):
36
+ self._log_with_caller(logging.DEBUG, msg, *args, caller=caller, **kwargs)
37
+
38
+ def warning(self, msg, *args, caller="Unknown", **kwargs):
39
+ self._log_with_caller(logging.WARNING, msg, *args, caller=caller, **kwargs)
40
+
41
+ def error(self, msg, *args, caller="Unknown", **kwargs):
42
+ self._log_with_caller(logging.ERROR, msg, *args, caller=caller, **kwargs)
43
+
44
+ def critical(self, msg, *args, caller="Unknown", **kwargs):
45
+ self._log_with_caller(logging.CRITICAL, msg, *args, caller=caller, **kwargs)
46
+
47
+
48
+ # Replace the default logger class with the custom one
49
+ logging.setLoggerClass(CustomLogger)
50
+
51
+
52
+ # Set up the user logger
53
+ def setup_user_logger(filename: str):
54
+ """
55
+ Sets up a user-specific logger that logs messages to a file.
56
+ Args:
57
+ filename (str): The base name of the file where logs will be stored.
58
+ The file will have a ".txt" extension.
59
+ Returns:
60
+ logging.Logger: A configured logger instance with a file handler and formatter.
61
+ Raises:
62
+ AssertionError: If the filename is not provided.
63
+ """
64
+
65
+ assert filename, "Filename must be provided"
66
+ user_logger = logging.getLogger("user_logger")
67
+ user_logger.setLevel(logging.DEBUG) # Enable all log levels
68
+
69
+ # Create a file handler to store logs in "LOG.txt"
70
+ user_handler = logging.FileHandler(filename)
71
+ user_handler.setLevel(logging.DEBUG) # Capture all log levels in the handler
72
+
73
+ # Create a formatter with caller information
74
+ user_formatter = logging.Formatter(
75
+ "|%(asctime)s|%(levelname)s|%(caller)s|%(message)s|"
76
+ )
77
+ user_handler.setFormatter(user_formatter)
78
+
79
+ # Add the handler to the logger
80
+ user_logger.addHandler(user_handler)
81
+ return user_logger
82
+
83
+
@@ -0,0 +1,73 @@
1
+ import logging
2
+ import inspect
3
+ from datetime import datetime
4
+ import os
5
+
6
+
7
+ class CustomLogger(logging.Logger):
8
+ """Custom logger that dynamically captures caller details."""
9
+
10
+ def _log_with_caller(self, level, msg, *args, **kwargs):
11
+ # Dynamically fetch the calling function's details
12
+ frame = inspect.stack()[2] # Get the caller's stack frame (2 levels up)
13
+ caller_file = os.path.basename(frame.filename) # Extract the filename
14
+ caller_func = frame.function # Extract the function name
15
+
16
+ # Add caller information to `extra`
17
+ extra = kwargs.get("extra", {})
18
+ extra["caller_file"] = caller_file
19
+ extra["caller_func"] = caller_func
20
+ kwargs["extra"] = extra
21
+
22
+ # Proceed with the standard logging
23
+ super().log(level, msg, *args, **kwargs)
24
+
25
+ def info(self, msg, *args, **kwargs):
26
+ self._log_with_caller(logging.INFO, msg, *args, **kwargs)
27
+
28
+ def debug(self, msg, *args, **kwargs):
29
+ self._log_with_caller(logging.DEBUG, msg, *args, **kwargs)
30
+
31
+ def warning(self, msg, *args, **kwargs):
32
+ self._log_with_caller(logging.WARNING, msg, *args, **kwargs)
33
+
34
+ def error(self, msg, *args, **kwargs):
35
+ self._log_with_caller(logging.ERROR, msg, *args, **kwargs)
36
+
37
+ def critical(self, msg, *args, **kwargs):
38
+ self._log_with_caller(logging.CRITICAL, msg, *args, **kwargs)
39
+
40
+
41
+ # Replace the default logger class with the custom one
42
+ logging.setLoggerClass(CustomLogger)
43
+
44
+
45
+ # Function to set up the user logger
46
+ def setup_user_logger():
47
+ """Sets up and returns the user logger."""
48
+ user_logger = logging.getLogger("user_logger")
49
+
50
+ # Ensure the "log" directory exists
51
+ os.makedirs("./log", exist_ok=True)
52
+
53
+ # Dynamically fetch the caller's filename for the log file
54
+ caller_file = os.path.splitext(os.path.basename(inspect.stack()[1].filename))[0]
55
+
56
+ # Create a file handler with a timestamped filename
57
+ log_filename = f"./log/{caller_file}_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.txt"
58
+ user_handler = logging.FileHandler(log_filename)
59
+ user_handler.setLevel(logging.DEBUG) # Capture all log levels
60
+
61
+ # Create a formatter with detailed caller information
62
+ user_formatter = logging.Formatter(
63
+ "%(asctime)s - %(levelname)s - %(caller_file)s - Function: %(caller_func)s - Line: %(caller_lineno)d - %(message)s"
64
+ )
65
+ user_handler.setFormatter(user_formatter)
66
+
67
+ # Add the handler to the logger
68
+ user_logger.addHandler(user_handler)
69
+ user_logger.setLevel(logging.DEBUG) # Enable all log levels
70
+ return user_logger
71
+
72
+
73
+