singleton-logger 0.1.0__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,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.4
2
+ Name: singleton-logger
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Requires-Python: >=3.14
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: pip>=26.2.1
9
+ Dynamic: license-file
10
+
11
+ # Run-time persistent Logger
12
+
13
+ ## Overview
14
+
15
+ **TLDR:** Gives the option to initialise the logger once (`Singleton`) across different modules while preventing/denying global access.
16
+
17
+ The provided logging suite offers a robust, crash-resilient mechanism for capturing software execution states. The architecture is designed to address the synchronisation of log events across multiple modules avoiding repetitive formal configuration. implementation deferred execution queue, the system ensures that early-stage initialisation logs are preserved and subsequently written to disk once the primary logging configuration is exited (halted or crashed).
18
+
19
+ ## Installation
20
+
21
+ ### Pypi
22
+
23
+ 1. Create your `.venv` as usual
24
+
25
+ 2. Add
26
+ ```bash
27
+ pip install -i https://test.pypi.org/simple/ singleton-logger
28
+ ```
29
+
30
+ 3. Import the module normally
31
+
32
+ ```python
33
+ from singleton_logger import Logger
34
+
35
+ def main() -> None:
36
+ log = Logger.get_logger( )
37
+ Logger.configure(
38
+ level_ = 10, #Debug
39
+ name_ = "main_logger"
40
+ )
41
+
42
+ log.debug("Message")
43
+ ```
44
+
45
+ ## Architectural Design
46
+
47
+ The framework employs a modified `Singleton` pattern to manage a non-global logging state. The architecture comprises three primary components: the central `Logger` class, a proxy `_Lazy_Logger` class, and a customised `Flushing_File_Handler`.
48
+
49
+ mermaid diagram
50
+
51
+ ![singleton-logger](./docs/art/singleton-logger.png)
52
+
53
+ ## Design Logic and Theoretical Framework
54
+
55
+ ### Deferred Execution and State Management
56
+
57
+ A significant challenge in distributed or multi-module software architectures is the instantiation of logging mechanisms before the central configuration is applied. Standard Python logging modules often discard or improperly route these early messages. The implementation resolves this through the `_Lazy_Logger` class. This proxy object captures logging method calls and arguments, storing them in memory. Upon the invocation of `Logger.configure()`, the queue is flushed to the permanent disk location. This behaviour ensures zero data loss during application bootstrapping.
58
+
59
+ ### Application of SOLID Principles
60
+
61
+ The design aligns with a couple SOLID principles, which was the inspiration for writing this project after discussion with some of my students.
62
+
63
+ **Single Responsibility Principle**: The `_Lazy_Logger` is strictly responsible for message queuing, while the Logger class manages file handles and configuration state.
64
+
65
+ **Open/Closed Principle**: The system can be extended with custom handlers, such as the `Flushing_File_Handler`, without modifying the core Logger class logic.
66
+
67
+ **Liskov Substitution Principle**: The `_Lazy_Logger` dynamically mimics the interface of a standard `logging.Logger` via the __getattr__ method, allowing it to serve as a transparent substitute for the underlying logging object.
68
+
69
+ ### Crash Resiliency
70
+
71
+ `Singleton-Logger` prioritizes message preservation during runtime error. By registering the `_cleanup` method with the `atexit` module, the suite ensures that all file buffers are flushed to the disk/file upon normal or abnormal termination. Additionally, the `Flushing_File_Handler` forces a disk write operation after every individual log emission, minimizing the risk of data loss from operating system buffering delays.
72
+
73
+ ### System Advantages
74
+
75
+ **Initialisation Safety**: Modules can safely request and utilize logger instances at import time without waiting for the primary application entry point to execute configuration parameters.
76
+
77
+ **Data Integrity**: The explicit use of the `atexit` registry and immediate file creation ensures that diagnostic information is captured even when unhandled exceptions occur.
78
+
79
+ **Centralised Configuration**: All module-level loggers inherit the formatting and output destinations defined during the single configure method call. This eliminates fragmented log files.
80
+
81
+ ### System Limitations
82
+
83
+ **Performance Overhead**: The stringent flushing protocols introduce significant disk input/output latency, particularly if `Flushing_File_Handler` is widely applied. Writing to disk after every event reduces the overall throughput of high-frequency execution paths.
84
+
85
+ **Memory Constraints**: If the application fails to call `Logger.configure()` in a timely manner, the `_Lazy_Logger` queue will expand indefinitely. In long-running applications that fail to initialize properly, this behaviour may lead to memory exhaustion.
86
+
87
+ **Singleton State Complexity**: The reliance on class-level attributes introduces global state. This design choice complicates unit testing, as test environments must explicitly reset the `_configured` flag and internal dictionaries between test suites to prevent state leakage.
88
+
89
+ ## Implementation Guidelines
90
+ The following code illustrates the intended usage paradigm for the suite.
91
+
92
+ in `main.py`, the first logger is initialized.
93
+
94
+ ```python
95
+ import os
96
+ import logging
97
+ import singleton_logger as Logger
98
+
99
+ from .do_something import do_something
100
+ from .do_something_else import do_something_else
101
+
102
+ def main():
103
+
104
+ Logger.configure(
105
+ level_ = logging.DEBUG, # integer values also available
106
+ name_ = "singleton_logger"
107
+ )
108
+
109
+ log = Logger.get_logger()
110
+ log.info( "Application initialized successfully" )
111
+
112
+ try:
113
+ do_something()
114
+
115
+ except Exception as e:
116
+
117
+ log.error( f"Critical failure: {e}" )
118
+ Logger.flush_all()
119
+ raise
120
+
121
+ do_something_else()
122
+ ```
123
+
124
+ in module `do_something.py`, logger gets the singleton if a new logger is not instantiated.
125
+
126
+ ```python
127
+ import Logger
128
+
129
+ def do_something():
130
+
131
+ log = Logger.get_logger("singleton_logger")
132
+ log.debug("Processing routine started")
133
+ ```
134
+
135
+ in module `do_something_else.py`
136
+
137
+ ```python
138
+ import Logger
139
+
140
+ def do_something_else():
141
+
142
+ log = Logger.get_logger("singleton_logger")
143
+ log.warning("Processing routine started")
144
+
145
+ ```
146
+
147
+ ## Future implementations
148
+
149
+ 1. Logger streams log messages via api, email, ...
150
+ 1. Improvements module ux, specially for `Logger.configuration`
151
+
152
+
153
+ ## References
154
+
155
+ Gamma, E., Helm, R., Johnson, R., & Vlissides, J. (1994). Design patterns: elements of reusable object-oriented software. Addison-Wesley.
156
+
157
+ Yuan, D., Zheng, J., Park, S., Zhou, Y., & Balaraman, S. (2012). Improving software diagnosability via log enhancement. ACM Transactions on Computer Systems (TOCS), 30(1), 1-28.
158
+
159
+ Fu, Q., Lou, J. G., Wang, Y., & Li, J. (2014). Execution anomaly detection in distributed systems through unstructured log analysis. In 2009 Ninth IEEE International Conference on Data Mining (pp. 149-158). IEEE.
160
+
161
+ ## Support
162
+
163
+ If you really want to support this and other projects that I am involved, you can buy me a coffee.
164
+
165
+ <img src="/home/contesini/00_keys/qr-code.png" alt="buymeacoffee" style="zoom: 25%;" />
166
+
167
+ Thank you,
168
+
169
+ And I hope you have a great day ahead.
@@ -0,0 +1,159 @@
1
+ # Run-time persistent Logger
2
+
3
+ ## Overview
4
+
5
+ **TLDR:** Gives the option to initialise the logger once (`Singleton`) across different modules while preventing/denying global access.
6
+
7
+ The provided logging suite offers a robust, crash-resilient mechanism for capturing software execution states. The architecture is designed to address the synchronisation of log events across multiple modules avoiding repetitive formal configuration. implementation deferred execution queue, the system ensures that early-stage initialisation logs are preserved and subsequently written to disk once the primary logging configuration is exited (halted or crashed).
8
+
9
+ ## Installation
10
+
11
+ ### Pypi
12
+
13
+ 1. Create your `.venv` as usual
14
+
15
+ 2. Add
16
+ ```bash
17
+ pip install -i https://test.pypi.org/simple/ singleton-logger
18
+ ```
19
+
20
+ 3. Import the module normally
21
+
22
+ ```python
23
+ from singleton_logger import Logger
24
+
25
+ def main() -> None:
26
+ log = Logger.get_logger( )
27
+ Logger.configure(
28
+ level_ = 10, #Debug
29
+ name_ = "main_logger"
30
+ )
31
+
32
+ log.debug("Message")
33
+ ```
34
+
35
+ ## Architectural Design
36
+
37
+ The framework employs a modified `Singleton` pattern to manage a non-global logging state. The architecture comprises three primary components: the central `Logger` class, a proxy `_Lazy_Logger` class, and a customised `Flushing_File_Handler`.
38
+
39
+ mermaid diagram
40
+
41
+ ![singleton-logger](./docs/art/singleton-logger.png)
42
+
43
+ ## Design Logic and Theoretical Framework
44
+
45
+ ### Deferred Execution and State Management
46
+
47
+ A significant challenge in distributed or multi-module software architectures is the instantiation of logging mechanisms before the central configuration is applied. Standard Python logging modules often discard or improperly route these early messages. The implementation resolves this through the `_Lazy_Logger` class. This proxy object captures logging method calls and arguments, storing them in memory. Upon the invocation of `Logger.configure()`, the queue is flushed to the permanent disk location. This behaviour ensures zero data loss during application bootstrapping.
48
+
49
+ ### Application of SOLID Principles
50
+
51
+ The design aligns with a couple SOLID principles, which was the inspiration for writing this project after discussion with some of my students.
52
+
53
+ **Single Responsibility Principle**: The `_Lazy_Logger` is strictly responsible for message queuing, while the Logger class manages file handles and configuration state.
54
+
55
+ **Open/Closed Principle**: The system can be extended with custom handlers, such as the `Flushing_File_Handler`, without modifying the core Logger class logic.
56
+
57
+ **Liskov Substitution Principle**: The `_Lazy_Logger` dynamically mimics the interface of a standard `logging.Logger` via the __getattr__ method, allowing it to serve as a transparent substitute for the underlying logging object.
58
+
59
+ ### Crash Resiliency
60
+
61
+ `Singleton-Logger` prioritizes message preservation during runtime error. By registering the `_cleanup` method with the `atexit` module, the suite ensures that all file buffers are flushed to the disk/file upon normal or abnormal termination. Additionally, the `Flushing_File_Handler` forces a disk write operation after every individual log emission, minimizing the risk of data loss from operating system buffering delays.
62
+
63
+ ### System Advantages
64
+
65
+ **Initialisation Safety**: Modules can safely request and utilize logger instances at import time without waiting for the primary application entry point to execute configuration parameters.
66
+
67
+ **Data Integrity**: The explicit use of the `atexit` registry and immediate file creation ensures that diagnostic information is captured even when unhandled exceptions occur.
68
+
69
+ **Centralised Configuration**: All module-level loggers inherit the formatting and output destinations defined during the single configure method call. This eliminates fragmented log files.
70
+
71
+ ### System Limitations
72
+
73
+ **Performance Overhead**: The stringent flushing protocols introduce significant disk input/output latency, particularly if `Flushing_File_Handler` is widely applied. Writing to disk after every event reduces the overall throughput of high-frequency execution paths.
74
+
75
+ **Memory Constraints**: If the application fails to call `Logger.configure()` in a timely manner, the `_Lazy_Logger` queue will expand indefinitely. In long-running applications that fail to initialize properly, this behaviour may lead to memory exhaustion.
76
+
77
+ **Singleton State Complexity**: The reliance on class-level attributes introduces global state. This design choice complicates unit testing, as test environments must explicitly reset the `_configured` flag and internal dictionaries between test suites to prevent state leakage.
78
+
79
+ ## Implementation Guidelines
80
+ The following code illustrates the intended usage paradigm for the suite.
81
+
82
+ in `main.py`, the first logger is initialized.
83
+
84
+ ```python
85
+ import os
86
+ import logging
87
+ import singleton_logger as Logger
88
+
89
+ from .do_something import do_something
90
+ from .do_something_else import do_something_else
91
+
92
+ def main():
93
+
94
+ Logger.configure(
95
+ level_ = logging.DEBUG, # integer values also available
96
+ name_ = "singleton_logger"
97
+ )
98
+
99
+ log = Logger.get_logger()
100
+ log.info( "Application initialized successfully" )
101
+
102
+ try:
103
+ do_something()
104
+
105
+ except Exception as e:
106
+
107
+ log.error( f"Critical failure: {e}" )
108
+ Logger.flush_all()
109
+ raise
110
+
111
+ do_something_else()
112
+ ```
113
+
114
+ in module `do_something.py`, logger gets the singleton if a new logger is not instantiated.
115
+
116
+ ```python
117
+ import Logger
118
+
119
+ def do_something():
120
+
121
+ log = Logger.get_logger("singleton_logger")
122
+ log.debug("Processing routine started")
123
+ ```
124
+
125
+ in module `do_something_else.py`
126
+
127
+ ```python
128
+ import Logger
129
+
130
+ def do_something_else():
131
+
132
+ log = Logger.get_logger("singleton_logger")
133
+ log.warning("Processing routine started")
134
+
135
+ ```
136
+
137
+ ## Future implementations
138
+
139
+ 1. Logger streams log messages via api, email, ...
140
+ 1. Improvements module ux, specially for `Logger.configuration`
141
+
142
+
143
+ ## References
144
+
145
+ Gamma, E., Helm, R., Johnson, R., & Vlissides, J. (1994). Design patterns: elements of reusable object-oriented software. Addison-Wesley.
146
+
147
+ Yuan, D., Zheng, J., Park, S., Zhou, Y., & Balaraman, S. (2012). Improving software diagnosability via log enhancement. ACM Transactions on Computer Systems (TOCS), 30(1), 1-28.
148
+
149
+ Fu, Q., Lou, J. G., Wang, Y., & Li, J. (2014). Execution anomaly detection in distributed systems through unstructured log analysis. In 2009 Ninth IEEE International Conference on Data Mining (pp. 149-158). IEEE.
150
+
151
+ ## Support
152
+
153
+ If you really want to support this and other projects that I am involved, you can buy me a coffee.
154
+
155
+ <img src="/home/contesini/00_keys/qr-code.png" alt="buymeacoffee" style="zoom: 25%;" />
156
+
157
+ Thank you,
158
+
159
+ And I hope you have a great day ahead.
@@ -0,0 +1,9 @@
1
+ [project]
2
+ name = "singleton-logger"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.14"
7
+ dependencies = [
8
+ "pip>=26.2.1",
9
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,7 @@
1
+ from .start_logger import Logger
2
+ from .start_logger import get_logger
3
+
4
+ __all__ = [
5
+ "Logger",
6
+ "get_logger"
7
+ ]
@@ -0,0 +1,285 @@
1
+
2
+ import os
3
+ import sys
4
+ import logging
5
+ import pathlib
6
+ import types
7
+ import typing
8
+
9
+ from atexit import register
10
+ from datetime import datetime
11
+ # ==============================================================================
12
+ class _Lazy_Logger( object ):
13
+
14
+ '''
15
+ Proxy logger that queues messages until Logger.configure() is called.
16
+ This allows modules to create log = get_logger() at import time.
17
+ '''
18
+
19
+ # ! Why standard python logging does not have this behaviour by default instead a global logger.
20
+
21
+ # ============================================================================
22
+ def __init__( self ) -> None:
23
+ self._queue : list = []
24
+ self._real_logger : logging.Logger | _Lazy_Logger | None = None
25
+
26
+ # ============================================================================
27
+ def _get_real_logger( self ):
28
+
29
+ if self._real_logger is None:
30
+
31
+ if Logger._configured:
32
+
33
+ self._real_logger : logging.Logger | _Lazy_Logger | None = Logger.get_global( )
34
+
35
+ for method, args, kwargs in self._queue:
36
+
37
+ getattr( self._real_logger, method )( *args, **kwargs )
38
+
39
+ self._queue.clear( )
40
+
41
+ return self._real_logger
42
+
43
+ # ============================================================================
44
+ def _log_method( self, method_name ) -> typing.Callable:
45
+
46
+ def method( *args, **kwargs ):
47
+
48
+ real : logging.Logger | None | _Lazy_Logger = self._get_real_logger( )
49
+
50
+ if real:
51
+ return getattr( real, method_name )( *args, **kwargs )
52
+
53
+ else:
54
+ self._queue.append( ( method_name, args, kwargs ) )
55
+
56
+ return method
57
+
58
+ # ============================================================================
59
+ def __getattr__( self, name ) -> typing.Callable:
60
+
61
+ return self._log_method( name )
62
+
63
+ # ==============================================================================
64
+ class Flushing_File_Handler( logging.FileHandler ):
65
+ '''
66
+ A file handler that flushes after every log entry.
67
+ Use this for maximum crash resistance at the cost of performance.
68
+ Custom logging handler that auto-flushes on every write (use for critical apps)
69
+ '''
70
+
71
+ def emit( self, record ) -> None:
72
+
73
+ super( ).emit( record )
74
+ self.flush( )
75
+
76
+ # ==============================================================================
77
+ def get_logger( ) -> logging.Logger | _Lazy_Logger | None:
78
+ '''
79
+ Returns the global LOG instance. Import and call this in every module.
80
+ '''
81
+
82
+ return Logger.get_global( )
83
+ # ==============================================================================
84
+ class Logger:
85
+ '''
86
+ A crash-resilient logger using Singleton design that maintains consistent
87
+ configuration across modules, ensuring logs are captured even during crashes.
88
+
89
+ # Example
90
+ #
91
+ # In your main.py
92
+
93
+ from log import Logger
94
+
95
+ logfile_name = basename(__file__).split('.')[0]
96
+ Logger.configure( name_ = logfile_name, level_ = log_level_)
97
+
98
+ def main():
99
+ log = logger.get_logger()
100
+ log.info( "This message gets queued" )
101
+
102
+ # In module:
103
+
104
+ from lib.log import Logger
105
+
106
+ def some_function( ):
107
+
108
+ log = logger.get_logger( )
109
+ log.info( "Function called" )
110
+
111
+ log.debug( "Debug info" )
112
+
113
+ try:
114
+ result = 1 / 0
115
+
116
+ except Exception as e:
117
+ log.debug( f"Error occurred {e}" )
118
+ Logger.flush_all( )
119
+ raise
120
+ '''
121
+
122
+ _loggers : dict = {}
123
+ _configured : bool = False
124
+ _console_level : int = logging.DEBUG
125
+ _file_handler : logging.FileHandler | None = None
126
+ _global_logger : logging.Logger | None = None
127
+ # ============================================================================
128
+ @classmethod
129
+ def configure(
130
+ cls,
131
+ name_ : str = "default",
132
+ level_ : int = logging.INFO,
133
+ var_log_dir_path_ : str = "./var/log/"
134
+ ) -> None | logging.Logger:
135
+
136
+ '''
137
+ Explicitly configure the logger. Call this once at program startup.
138
+ Creates the log file immediately to ensure crash logs are captured.
139
+ '''
140
+
141
+ if cls._configured:
142
+ return cls._global_logger
143
+
144
+ _logfile_folder = var_log_dir_path_
145
+ _logfile_format : str = f"{_logfile_folder}_{name_}_{datetime.today( ).strftime( '%Y-%m-%d_-_%H-%M-%S' )}.log"
146
+
147
+ cls._logfile = _logfile_format
148
+ cls._console_level = level_
149
+
150
+ log_path = pathlib.Path( cls._logfile )
151
+
152
+ if not log_path.parent.exists( ):
153
+
154
+ try:
155
+ os.makedirs( log_path.parent, exist_ok = True )
156
+
157
+ except PermissionError as _:
158
+ print( f"WARNING {_}: Permission denied creating {log_path.parent}, logs file may fail" )
159
+
160
+ try:
161
+ with open( cls._logfile, 'a', encoding='utf-8' ) as _file:
162
+ _file.write( f"=== Log initialized at {datetime.now( )} ===\n" )
163
+
164
+ except Exception as e:
165
+ print( f"WARNING: LOG FILE COULD NOT BE CREATED: {e}" )
166
+
167
+ cls._configured = True
168
+
169
+ # Create the global LOG instance
170
+ cls._global_logger = cls._create_logger( "GLOBAL" )
171
+
172
+ register( cls._cleanup )
173
+
174
+ return cls._global_logger
175
+
176
+ # ============================================================================
177
+ @classmethod
178
+ def _create_logger(
179
+ cls,
180
+ name_ : str = "default",
181
+ log_format_ : str = "%(asctime)s | %(name)s | %(funcName)s.%(lineno)d | %(levelname)s | %(message)s",
182
+ date_format_ : str = "%Y-%m-%d %H:%M:%S",
183
+ ) -> logging.Logger:
184
+
185
+ '''
186
+ Internal method for logger instance.
187
+ '''
188
+
189
+ if name_ in cls._loggers:
190
+ return cls._loggers[ name_ ]
191
+
192
+ logger : logging.Logger = logging.getLogger( name_ )
193
+ logger.setLevel( logging.DEBUG )
194
+
195
+ logger.handlers.clear( )
196
+
197
+ formatter = logging.Formatter(
198
+ fmt = log_format_,
199
+ datefmt = date_format_
200
+ )
201
+
202
+ try:
203
+ file_handler = logging.FileHandler(
204
+ cls._logfile,
205
+ mode = "a",
206
+ encoding = "utf-8"
207
+ )
208
+
209
+ # Debug is default
210
+ file_handler.setLevel( logging.DEBUG )
211
+ file_handler.setFormatter( formatter )
212
+
213
+ if cls._file_handler is None:
214
+ cls._file_handler = file_handler
215
+
216
+ logger.addHandler( file_handler )
217
+
218
+ except Exception as e:
219
+ print( f"Warning: Cannot create file handler: {e}" )
220
+
221
+ cli_handler = logging.StreamHandler( sys.stdout )
222
+ cli_handler.setLevel( cls._console_level )
223
+ cli_handler.setFormatter( formatter )
224
+ logger.addHandler( cli_handler )
225
+
226
+ cls._loggers[ name_ ] = logger
227
+
228
+ return logger
229
+
230
+ # ============================================================================
231
+ @classmethod
232
+ def get_logger(
233
+ cls,
234
+ name_ : str = "default",
235
+ ) -> _Lazy_Logger | logging.Logger:
236
+
237
+ '''
238
+ Returns a configured logger with immediate disk flushing.
239
+ If not configured yet, returns the global logger which will be properly
240
+ initialized when configure() is called.
241
+ '''
242
+ # If asking for global or not configured logger, return global logger
243
+ if not cls._configured:
244
+ return _Lazy_Logger( )
245
+
246
+ _name : str = name_
247
+ if name_ == "default" :
248
+ _frame : types.FrameType= sys._getframe( 1 )
249
+ _filepath : pathlib.Path = pathlib.Path( _frame.f_code.co_filename )
250
+ _name = _filepath.stem
251
+
252
+ return cls._create_logger( _name )
253
+ # ============================================================================
254
+ @classmethod
255
+ def get_global( cls ) -> _Lazy_Logger | logging.Logger | None:
256
+ '''
257
+ Returns the global LOG instance. Use this for the global LOG object.
258
+ '''
259
+
260
+ if not cls._configured:
261
+ return _Lazy_Logger( )
262
+
263
+ return cls._global_logger
264
+ # ============================================================================
265
+ @classmethod
266
+ def _cleanup( cls ) -> None:
267
+ '''Ensure all handlers are properly flushed and closed.'''
268
+
269
+ for logger in cls._loggers.values( ):
270
+
271
+ for handler in logger.handlers:
272
+
273
+ handler.flush( )
274
+ handler.close( )
275
+
276
+ # ============================================================================
277
+ @classmethod
278
+ def flush_all( cls ) -> None:
279
+ '''Manually flush all log handlers. Call this before risky operations.'''
280
+
281
+ for logger in cls._loggers.values( ):
282
+ for handler in logger.handlers:
283
+ handler.flush( )
284
+
285
+ # ==============================================================================
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.4
2
+ Name: singleton-logger
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Requires-Python: >=3.14
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: pip>=26.2.1
9
+ Dynamic: license-file
10
+
11
+ # Run-time persistent Logger
12
+
13
+ ## Overview
14
+
15
+ **TLDR:** Gives the option to initialise the logger once (`Singleton`) across different modules while preventing/denying global access.
16
+
17
+ The provided logging suite offers a robust, crash-resilient mechanism for capturing software execution states. The architecture is designed to address the synchronisation of log events across multiple modules avoiding repetitive formal configuration. implementation deferred execution queue, the system ensures that early-stage initialisation logs are preserved and subsequently written to disk once the primary logging configuration is exited (halted or crashed).
18
+
19
+ ## Installation
20
+
21
+ ### Pypi
22
+
23
+ 1. Create your `.venv` as usual
24
+
25
+ 2. Add
26
+ ```bash
27
+ pip install -i https://test.pypi.org/simple/ singleton-logger
28
+ ```
29
+
30
+ 3. Import the module normally
31
+
32
+ ```python
33
+ from singleton_logger import Logger
34
+
35
+ def main() -> None:
36
+ log = Logger.get_logger( )
37
+ Logger.configure(
38
+ level_ = 10, #Debug
39
+ name_ = "main_logger"
40
+ )
41
+
42
+ log.debug("Message")
43
+ ```
44
+
45
+ ## Architectural Design
46
+
47
+ The framework employs a modified `Singleton` pattern to manage a non-global logging state. The architecture comprises three primary components: the central `Logger` class, a proxy `_Lazy_Logger` class, and a customised `Flushing_File_Handler`.
48
+
49
+ mermaid diagram
50
+
51
+ ![singleton-logger](./docs/art/singleton-logger.png)
52
+
53
+ ## Design Logic and Theoretical Framework
54
+
55
+ ### Deferred Execution and State Management
56
+
57
+ A significant challenge in distributed or multi-module software architectures is the instantiation of logging mechanisms before the central configuration is applied. Standard Python logging modules often discard or improperly route these early messages. The implementation resolves this through the `_Lazy_Logger` class. This proxy object captures logging method calls and arguments, storing them in memory. Upon the invocation of `Logger.configure()`, the queue is flushed to the permanent disk location. This behaviour ensures zero data loss during application bootstrapping.
58
+
59
+ ### Application of SOLID Principles
60
+
61
+ The design aligns with a couple SOLID principles, which was the inspiration for writing this project after discussion with some of my students.
62
+
63
+ **Single Responsibility Principle**: The `_Lazy_Logger` is strictly responsible for message queuing, while the Logger class manages file handles and configuration state.
64
+
65
+ **Open/Closed Principle**: The system can be extended with custom handlers, such as the `Flushing_File_Handler`, without modifying the core Logger class logic.
66
+
67
+ **Liskov Substitution Principle**: The `_Lazy_Logger` dynamically mimics the interface of a standard `logging.Logger` via the __getattr__ method, allowing it to serve as a transparent substitute for the underlying logging object.
68
+
69
+ ### Crash Resiliency
70
+
71
+ `Singleton-Logger` prioritizes message preservation during runtime error. By registering the `_cleanup` method with the `atexit` module, the suite ensures that all file buffers are flushed to the disk/file upon normal or abnormal termination. Additionally, the `Flushing_File_Handler` forces a disk write operation after every individual log emission, minimizing the risk of data loss from operating system buffering delays.
72
+
73
+ ### System Advantages
74
+
75
+ **Initialisation Safety**: Modules can safely request and utilize logger instances at import time without waiting for the primary application entry point to execute configuration parameters.
76
+
77
+ **Data Integrity**: The explicit use of the `atexit` registry and immediate file creation ensures that diagnostic information is captured even when unhandled exceptions occur.
78
+
79
+ **Centralised Configuration**: All module-level loggers inherit the formatting and output destinations defined during the single configure method call. This eliminates fragmented log files.
80
+
81
+ ### System Limitations
82
+
83
+ **Performance Overhead**: The stringent flushing protocols introduce significant disk input/output latency, particularly if `Flushing_File_Handler` is widely applied. Writing to disk after every event reduces the overall throughput of high-frequency execution paths.
84
+
85
+ **Memory Constraints**: If the application fails to call `Logger.configure()` in a timely manner, the `_Lazy_Logger` queue will expand indefinitely. In long-running applications that fail to initialize properly, this behaviour may lead to memory exhaustion.
86
+
87
+ **Singleton State Complexity**: The reliance on class-level attributes introduces global state. This design choice complicates unit testing, as test environments must explicitly reset the `_configured` flag and internal dictionaries between test suites to prevent state leakage.
88
+
89
+ ## Implementation Guidelines
90
+ The following code illustrates the intended usage paradigm for the suite.
91
+
92
+ in `main.py`, the first logger is initialized.
93
+
94
+ ```python
95
+ import os
96
+ import logging
97
+ import singleton_logger as Logger
98
+
99
+ from .do_something import do_something
100
+ from .do_something_else import do_something_else
101
+
102
+ def main():
103
+
104
+ Logger.configure(
105
+ level_ = logging.DEBUG, # integer values also available
106
+ name_ = "singleton_logger"
107
+ )
108
+
109
+ log = Logger.get_logger()
110
+ log.info( "Application initialized successfully" )
111
+
112
+ try:
113
+ do_something()
114
+
115
+ except Exception as e:
116
+
117
+ log.error( f"Critical failure: {e}" )
118
+ Logger.flush_all()
119
+ raise
120
+
121
+ do_something_else()
122
+ ```
123
+
124
+ in module `do_something.py`, logger gets the singleton if a new logger is not instantiated.
125
+
126
+ ```python
127
+ import Logger
128
+
129
+ def do_something():
130
+
131
+ log = Logger.get_logger("singleton_logger")
132
+ log.debug("Processing routine started")
133
+ ```
134
+
135
+ in module `do_something_else.py`
136
+
137
+ ```python
138
+ import Logger
139
+
140
+ def do_something_else():
141
+
142
+ log = Logger.get_logger("singleton_logger")
143
+ log.warning("Processing routine started")
144
+
145
+ ```
146
+
147
+ ## Future implementations
148
+
149
+ 1. Logger streams log messages via api, email, ...
150
+ 1. Improvements module ux, specially for `Logger.configuration`
151
+
152
+
153
+ ## References
154
+
155
+ Gamma, E., Helm, R., Johnson, R., & Vlissides, J. (1994). Design patterns: elements of reusable object-oriented software. Addison-Wesley.
156
+
157
+ Yuan, D., Zheng, J., Park, S., Zhou, Y., & Balaraman, S. (2012). Improving software diagnosability via log enhancement. ACM Transactions on Computer Systems (TOCS), 30(1), 1-28.
158
+
159
+ Fu, Q., Lou, J. G., Wang, Y., & Li, J. (2014). Execution anomaly detection in distributed systems through unstructured log analysis. In 2009 Ninth IEEE International Conference on Data Mining (pp. 149-158). IEEE.
160
+
161
+ ## Support
162
+
163
+ If you really want to support this and other projects that I am involved, you can buy me a coffee.
164
+
165
+ <img src="/home/contesini/00_keys/qr-code.png" alt="buymeacoffee" style="zoom: 25%;" />
166
+
167
+ Thank you,
168
+
169
+ And I hope you have a great day ahead.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/singleton_logger/__init__.py
5
+ src/singleton_logger/start_logger.py
6
+ src/singleton_logger.egg-info/PKG-INFO
7
+ src/singleton_logger.egg-info/SOURCES.txt
8
+ src/singleton_logger.egg-info/dependency_links.txt
9
+ src/singleton_logger.egg-info/requires.txt
10
+ src/singleton_logger.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ singleton_logger