SwiftGUI_Logging 0.0.2__tar.gz → 0.1.1__tar.gz

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.
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: SwiftGUI_Logging
3
+ Version: 0.1.1
4
+ Summary: A collection of helpful logging-functionality based on the logging package
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Author: Eric aka CheesecakeTV
8
+ Author-email: cheesecaketv53+pypi@gmail.com
9
+ Requires-Python: >=3.10
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Project-URL: Documentation, https://github.com/CheesecakeTV/SwiftGUI-Docs
13
+ Project-URL: Repository, https://github.com/CheesecakeTV/SwiftGUI-Logging
14
+ Project-URL: issues, https://github.com/CheesecakeTV/SwiftGUI/issues
15
+ Description-Content-Type: text/markdown
16
+
17
+
18
+ # SwiftGUI-Logging: Motivation
19
+ A small package ment to extend logging to better fit actual applications.
20
+
21
+ Before getting into the logging-package, I usually implemented
22
+ something like this (but more complicated):
23
+ ```py
24
+ def main():
25
+ ...
26
+
27
+ if __name__ == "__main__":
28
+ try:
29
+ main() # Run the main program
30
+ except Exception as ex: # An exception occured
31
+ with open("Crashlog.txt", "w") as f: # Save exception to file
32
+ f.write(str(ex))
33
+ ```
34
+ If `main()` causes an exception, the file `Crashlog.txt` is created
35
+ containing information about the exception.
36
+ That means, only "the interesting logs" take up storage space.
37
+
38
+ Unfortunately, you can't implement such a functionality using the
39
+ logging-package.
40
+
41
+ Until now.
42
+
43
+ SwiftGUI-Logging provides a very easy way to set up crashlogs that
44
+ are fully compatible with the logging-package.
45
+
46
+ # Basic usage
47
+ ## Installation
48
+ Install the package by running this on your terminal:
49
+ ```bash
50
+ pip install SwiftGUI_Logging
51
+ ```
52
+
53
+ ## Crashlogging to a file
54
+ Simply call `SwiftGUI_Logging.Configs.exceptions_to_file(filepath)`
55
+ to set up the crashlogger.
56
+
57
+ That's all.
58
+
59
+ Example:
60
+ ```py
61
+ import time
62
+ import SwiftGUI_Logging as sgl
63
+ import logging
64
+
65
+ def main():
66
+ for i in range(10):
67
+ logging.debug(f"Test {i}")
68
+ print(i)
69
+ time.sleep(0.25)
70
+
71
+ logging.info("Crashing the program now")
72
+
73
+ 1 / 0 # Cause a ZeroDivisionError, which crashes the program
74
+
75
+ if __name__ == '__main__':
76
+ sgl.Configs.exceptions_to_file("Crashlogs/Crash.log") # Set up the crash-log
77
+ main() # Execute program
78
+ ```
79
+
80
+ You'll find that the directory `Crashlogs` was created.
81
+ After the program executes, the directory contains a file like
82
+ `Crash_2026-02-24_16-16-38.log`.
83
+
84
+ As you can see, the time of the crash was inserted into the
85
+ filename, so that multiple crashlogs don't overwrite each other.
86
+
87
+ `sgl.Configs.exceptions_to_file` can do a bit more, but for most programs,
88
+ the default configuration is fine.
89
+
90
+ ## Other functionality
91
+ `SwiftGUI_Logging` provides some other functionality, but these
92
+ aren't nearly as important as the `exceptions_to_file`-function.
93
+
94
+ A detailed documentation will follow.
95
+
96
+ # SwiftGUI
97
+ This package was written as an addition to
98
+ my Python GUI-package `SwiftGUI`:
99
+ https://github.com/CheesecakeTV/SwiftGUI
100
+
101
+ Since `SwiftGUI_Logging` itself has nothing to to with GUIs,
102
+ it is its own package.
103
+
104
+ Consider checking out `SwiftGUI` if you want to easily create
105
+ user-interfaces for python.
106
+ If you already know the package `PySimpleGUI`, you'll learn the
107
+ basics of`SwiftGUI` with little to no effort.
108
+
109
+
110
+
@@ -0,0 +1,93 @@
1
+
2
+ # SwiftGUI-Logging: Motivation
3
+ A small package ment to extend logging to better fit actual applications.
4
+
5
+ Before getting into the logging-package, I usually implemented
6
+ something like this (but more complicated):
7
+ ```py
8
+ def main():
9
+ ...
10
+
11
+ if __name__ == "__main__":
12
+ try:
13
+ main() # Run the main program
14
+ except Exception as ex: # An exception occured
15
+ with open("Crashlog.txt", "w") as f: # Save exception to file
16
+ f.write(str(ex))
17
+ ```
18
+ If `main()` causes an exception, the file `Crashlog.txt` is created
19
+ containing information about the exception.
20
+ That means, only "the interesting logs" take up storage space.
21
+
22
+ Unfortunately, you can't implement such a functionality using the
23
+ logging-package.
24
+
25
+ Until now.
26
+
27
+ SwiftGUI-Logging provides a very easy way to set up crashlogs that
28
+ are fully compatible with the logging-package.
29
+
30
+ # Basic usage
31
+ ## Installation
32
+ Install the package by running this on your terminal:
33
+ ```bash
34
+ pip install SwiftGUI_Logging
35
+ ```
36
+
37
+ ## Crashlogging to a file
38
+ Simply call `SwiftGUI_Logging.Configs.exceptions_to_file(filepath)`
39
+ to set up the crashlogger.
40
+
41
+ That's all.
42
+
43
+ Example:
44
+ ```py
45
+ import time
46
+ import SwiftGUI_Logging as sgl
47
+ import logging
48
+
49
+ def main():
50
+ for i in range(10):
51
+ logging.debug(f"Test {i}")
52
+ print(i)
53
+ time.sleep(0.25)
54
+
55
+ logging.info("Crashing the program now")
56
+
57
+ 1 / 0 # Cause a ZeroDivisionError, which crashes the program
58
+
59
+ if __name__ == '__main__':
60
+ sgl.Configs.exceptions_to_file("Crashlogs/Crash.log") # Set up the crash-log
61
+ main() # Execute program
62
+ ```
63
+
64
+ You'll find that the directory `Crashlogs` was created.
65
+ After the program executes, the directory contains a file like
66
+ `Crash_2026-02-24_16-16-38.log`.
67
+
68
+ As you can see, the time of the crash was inserted into the
69
+ filename, so that multiple crashlogs don't overwrite each other.
70
+
71
+ `sgl.Configs.exceptions_to_file` can do a bit more, but for most programs,
72
+ the default configuration is fine.
73
+
74
+ ## Other functionality
75
+ `SwiftGUI_Logging` provides some other functionality, but these
76
+ aren't nearly as important as the `exceptions_to_file`-function.
77
+
78
+ A detailed documentation will follow.
79
+
80
+ # SwiftGUI
81
+ This package was written as an addition to
82
+ my Python GUI-package `SwiftGUI`:
83
+ https://github.com/CheesecakeTV/SwiftGUI
84
+
85
+ Since `SwiftGUI_Logging` itself has nothing to to with GUIs,
86
+ it is its own package.
87
+
88
+ Consider checking out `SwiftGUI` if you want to easily create
89
+ user-interfaces for python.
90
+ If you already know the package `PySimpleGUI`, you'll learn the
91
+ basics of`SwiftGUI` with little to no effort.
92
+
93
+
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "SwiftGUI_Logging"
3
- version = "0.0.2"
3
+ version = "0.1.1"
4
4
  packages = [
5
5
  { include = "SwiftGUI_Logging", from = "src" }
6
6
  ]
@@ -0,0 +1,75 @@
1
+ import SwiftGUI_Logging as sgl
2
+ from pathlib import Path
3
+ import logging
4
+ from datetime import datetime as dt
5
+ import io
6
+ import shutil
7
+
8
+ def exceptions_to_file(
9
+ filepath: str | Path,
10
+ logger: str | logging.Logger = "",
11
+ buffer_size: int = 5000,
12
+ trigger_level: int = logging.ERROR,
13
+ log_level: int = logging.DEBUG,
14
+ reraise: bool = False,
15
+ datetime_format: str = "_%Y-%m-%d_%H-%M-%S",
16
+ formatter_format: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
17
+ ):
18
+ """
19
+ Buffers the last n logging-entries.
20
+ If the program executes as expected, nothing happens.
21
+ If an exception crashes the program, the whole buffer is logged to a file, including the exception.
22
+
23
+ This is also true if the logger receives a report of loglevel higher than the specified trigger.
24
+
25
+ Every filesave generates its own file with a timestamp in the name.
26
+
27
+ :param filepath: Path to a log-file WITHOUT THE TIMESTAMP. The timestamp is added at the end before the suffix.
28
+ :param logger: You can specify which logger should receive the exception-logs.
29
+ :param buffer_size: How many reports are saved before the first ones are overritten again
30
+ :param trigger_level: Level at which the exceptions are treated. Reports at and above this level trigger a file-write
31
+ :param log_level: Logs below this level are ignored and not written to the file
32
+ :param reraise: True, if the exception should still be raised, even though it was logged. Good for debugging purposes
33
+ :param datetime_format: Format of the timestamp that extends the filename
34
+ :param formatter_format: Format of the log-entries in the file
35
+ :return:
36
+ """
37
+ filepath = Path(filepath)
38
+ filepath.parent.mkdir(parents=True, exist_ok=True)
39
+
40
+ if isinstance(logger, str):
41
+ logger = logging.getLogger(logger)
42
+
43
+ logger.setLevel(log_level)
44
+
45
+ stream = io.StringIO()
46
+ stream_handler = logging.StreamHandler(stream)
47
+ stream_handler.setFormatter(
48
+ logging.Formatter(formatter_format)
49
+ )
50
+
51
+ def exception_occured(*_):
52
+ nonlocal stream
53
+ stream.seek(0)
54
+
55
+ if not stream.read(1):
56
+ # Nothing to report
57
+ return
58
+
59
+ # Add current datetime to filename
60
+ actual_filepath = filepath.parent / (filepath.stem + dt.now().strftime(datetime_format) + filepath.suffix)
61
+
62
+ with open(actual_filepath, "w") as f:
63
+ stream.seek(0)
64
+ shutil.copyfileobj(stream, f)
65
+
66
+ stream.close()
67
+ stream = io.StringIO() # "Clear" the buffer
68
+ stream_handler.setStream(stream)
69
+
70
+ buffer_handler = sgl.MemoryHandlerRotatingBuffer(buffer_size, trigger_level, target=stream_handler, call_after_flushing=exception_occured)
71
+
72
+ logger.addHandler(buffer_handler)
73
+
74
+ sgl.reroute_exceptions(logger, reraise=reraise, loglevel=trigger_level, pass_text_to_function=exception_occured)
75
+
@@ -0,0 +1,3 @@
1
+
2
+ from .ExceptionLogging import exceptions_to_file
3
+
@@ -0,0 +1,64 @@
1
+ import logging.handlers
2
+ import traceback
3
+ import sys
4
+ from typing import Callable, Any
5
+
6
+
7
+ def reroute_exceptions(
8
+ logger: logging.Logger = logging.getLogger(),
9
+ loglevel: int = logging.CRITICAL,
10
+ *,
11
+ logger_warnings: logging.Logger = None,
12
+ loglevel_warnings: int = logging.WARNING,
13
+ reraise: bool = False,
14
+ print_to_console: bool = False,
15
+ pass_text_to_function: Callable[[str], Any] = None,
16
+ ):
17
+ """
18
+ Catch all unhandled exceptions and log them
19
+
20
+ :param logger: The logger where EXCEPTIONS go
21
+ :param loglevel: The loglevel for EXCEPTIONS
22
+ :param logger_warnings: The logger where WARNINGS go
23
+ :param loglevel_warnings: The level of logging for WARNINGS
24
+ :param reraise: True, if the exception should be raised again
25
+ :param pass_text_to_function: Pass a function/method and the exception-text is passed to it
26
+ :param print_to_console: True, if the text should be printed to the console using print(...)
27
+ :return:
28
+ """
29
+ if logger_warnings is None:
30
+ logger_warnings = logger
31
+
32
+ if loglevel_warnings is None:
33
+ loglevel_warnings = loglevel
34
+
35
+ def catch(exctype, value, tb):
36
+ text = "".join(traceback.format_exception(exctype, value, tb))
37
+
38
+ if issubclass(exctype, Warning): # Warnings
39
+ if logger_warnings is not None:
40
+ logger_warnings.log(
41
+ loglevel_warnings,
42
+ text,
43
+ )
44
+ elif issubclass(exctype, Exception): # Real exceptions
45
+ if logger is not None:
46
+ logger.log(
47
+ loglevel,
48
+ text,
49
+ )
50
+ else:
51
+ # Keyboard interrupts and such
52
+ sys.__excepthook__(exctype, value, tb)
53
+ return # Not really necessary
54
+
55
+ if pass_text_to_function:
56
+ pass_text_to_function(text)
57
+
58
+ if print_to_console:
59
+ print(text)
60
+
61
+ if reraise:
62
+ sys.__excepthook__(exctype, value, tb)
63
+
64
+ sys.excepthook = catch
@@ -0,0 +1,39 @@
1
+ import logging.handlers
2
+ from typing import Callable
3
+
4
+
5
+ class MemoryHandlerRotatingBuffer(logging.handlers.MemoryHandler):
6
+
7
+ def __init__(self, capacity, flushLevel=logging.ERROR, target=None, call_after_flushing: Callable = None):
8
+ """
9
+ This handler saves the last n records.
10
+ Following records replace the oldest ones.
11
+ If something with a higher level than 'flushLevel' is logged, the handler passes all entries to another, specified handler.
12
+
13
+ THE BUFFER STILL FLUSHES WHEN THE SCRIPT ENDS, I COULDN'T AVOID THAT...
14
+ Happy for suggestions.
15
+
16
+ :param capacity: How many records to buffer before the oldest ones get deleted
17
+ :param flushLevel: At which level of record the whole buffer is passed to the target-handler
18
+ :param call_after_flushing: Call this function after passing the entries to the target
19
+ :param target: Handler to receive all records if necessary
20
+ """
21
+ super().__init__(capacity, flushLevel, target, flushOnClose=False)
22
+ self.call_after_flushing = call_after_flushing if call_after_flushing else lambda *_:_
23
+
24
+ def shouldFlush(self, record):
25
+ """
26
+ New records are checked if the "flushing-condition" is met.
27
+ :param record:
28
+ :return:
29
+ """
30
+ if len(self.buffer) > self.capacity: # Remove 0th element so the buffer doesn't "overflow"
31
+ self.buffer.pop(0)
32
+
33
+ return record.levelno >= self.flushLevel
34
+
35
+ def flush(self):
36
+ super().flush()
37
+ self.call_after_flushing()
38
+
39
+
@@ -0,0 +1,12 @@
1
+ import logging
2
+
3
+
4
+ def disable_root_handlers():
5
+ """
6
+ Remove all root handlers so the root handler does nothing.
7
+ Useful when you want to generate the logging-system from ground up
8
+ :return:
9
+ """
10
+ logging.getLogger().handlers.clear()
11
+ logging.getLogger().addHandler(logging.NullHandler())
12
+
@@ -0,0 +1,9 @@
1
+
2
+ from .ExceptionHandling import reroute_exceptions
3
+ from .MemoryHandlerRotatingBuffer import MemoryHandlerRotatingBuffer
4
+ from .Utils import disable_root_handlers
5
+
6
+ from . import Configs
7
+
8
+
9
+
@@ -1,21 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: SwiftGUI_Logging
3
- Version: 0.0.2
4
- Summary: A collection of helpful logging-functionality based on the logging package
5
- License-Expression: Apache-2.0
6
- License-File: LICENSE
7
- Author: Eric aka CheesecakeTV
8
- Author-email: cheesecaketv53+pypi@gmail.com
9
- Requires-Python: >=3.10
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Operating System :: OS Independent
12
- Project-URL: Documentation, https://github.com/CheesecakeTV/SwiftGUI-Docs
13
- Project-URL: Repository, https://github.com/CheesecakeTV/SwiftGUI-Logging
14
- Project-URL: issues, https://github.com/CheesecakeTV/SwiftGUI/issues
15
- Description-Content-Type: text/markdown
16
-
17
-
18
- # SwiftGUI-Logging
19
-
20
- Still WIP
21
-
@@ -1,4 +0,0 @@
1
-
2
- # SwiftGUI-Logging
3
-
4
- Still WIP
@@ -1,3 +0,0 @@
1
-
2
- from . import test
3
- print("WIP")
File without changes