Browse code

move main logging configuration to import time

When using nord as a library one does not have to set up explicit
logging. This does not noticeably slow down importing nord.

Joseph Weston authored on 15/04/2018 13:54:17
Showing 2 changed files
... ...
@@ -16,7 +16,38 @@
16 16
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 17
 """NordVPN client."""
18 18
 
19
+import logging
20
+import structlog
21
+
19 22
 from ._version import __version__
20 23
 del _version  # pylint: disable=undefined-variable
21 24
 
22 25
 from . import vpn, api
26
+
27
+
28
+# Set up default logging on import, in case nord is used as a library
29
+
30
+structlog.configure(
31
+    processors=[
32
+        structlog.stdlib.filter_by_level,
33
+        structlog.stdlib.add_logger_name,
34
+        structlog.stdlib.add_log_level,
35
+        structlog.processors.TimeStamper(fmt="%x:%X", utc=False),
36
+        structlog.processors.UnicodeDecoder(),
37
+    ],
38
+    logger_factory=structlog.stdlib.LoggerFactory(),
39
+    wrapper_class=structlog.stdlib.BoundLogger,
40
+    cache_logger_on_first_use=True,
41
+    context_class=dict,
42
+)
43
+
44
+# pylint: disable=protected-access
45
+structlog.stdlib.TRACE = 5
46
+structlog.stdlib._NAME_TO_LEVEL['trace'] = 5
47
+structlog.stdlib._LEVEL_TO_NAME[5] = 'trace'
48
+logging.addLevelName(5, "TRACE")
49
+
50
+# Even after we remove these references, these are still present in
51
+# sys.modules, so they remain loaded.
52
+del structlog
53
+del logging
... ...
@@ -92,28 +92,9 @@ def render_logs(logger, _, event):
92 92
 
93 93
 def setup_logging(args):
94 94
     """Set up logging."""
95
-    structlog.configure(
96
-        processors=[
97
-            structlog.stdlib.filter_by_level,
98
-            structlog.stdlib.add_logger_name,
99
-            structlog.stdlib.add_log_level,
100
-            structlog.processors.TimeStamper(fmt="%x:%X", utc=False),
101
-            structlog.processors.UnicodeDecoder(),
102
-            render_logs,
103
-        ],
104
-        context_class=dict,
105
-        logger_factory=structlog.stdlib.LoggerFactory(),
106
-        wrapper_class=structlog.stdlib.BoundLogger,
107
-        cache_logger_on_first_use=True,
108
-    )
95
+    cfg = structlog.get_config()
96
+    cfg['processors'].append(render_logs)
109 97
 
110
-    # set up stdlib logging to be the most permissive, structlog
111
-    # will handle all filtering and formatting
112
-    # pylint: disable=protected-access
113
-    structlog.stdlib.TRACE = 5
114
-    structlog.stdlib._NAME_TO_LEVEL['trace'] = 5
115
-    structlog.stdlib._LEVEL_TO_NAME[5] = 'trace'
116
-    logging.addLevelName(5, "TRACE")
117 98
     logging.basicConfig(
118 99
         stream=sys.stdout,
119 100
         level=(logging.DEBUG if hasattr(args, 'debug') and args.debug