5
5
6
6
import click
7
7
import connexion
8
+ import logging
8
9
9
10
from connexion .resolver import RestyResolver
10
11
from landoapi .dockerflow import dockerflow
11
12
from landoapi .models .storage import alembic , db
13
+ from mozlogging import MozLogFormatter
14
+
15
+ logger = logging .getLogger (__name__ )
12
16
13
17
14
18
def create_app (version_path ):
15
19
"""Construct an application instance."""
20
+ initialize_logging ()
21
+
16
22
app = connexion .App (__name__ , specification_dir = 'spec/' )
17
23
app .add_api ('swagger.yml' , resolver = RestyResolver ('landoapi.api' ))
18
24
@@ -36,6 +42,42 @@ def create_app(version_path):
36
42
return app
37
43
38
44
45
+ def initialize_logging ():
46
+ """Initialize application-wide logging."""
47
+ mozlog_handler = logging .StreamHandler ()
48
+ mozlog_handler .setFormatter (MozLogFormatter ())
49
+
50
+ # We need to configure the logger just for our application code. This is
51
+ # because the MozLogFormatter changes the signature of the standard
52
+ # library logging functions. Any code that tries to log a message assuming
53
+ # the standard library's formatter is in place, such as the code in the
54
+ # libraries we use, with throw an error if the MozLogFormatter tries to
55
+ # handle the message.
56
+ app_logger = logging .getLogger ('landoapi' )
57
+
58
+ app_logger .addHandler (mozlog_handler )
59
+
60
+ app_logger .setLevel (log_level_from_environ ())
61
+
62
+ logger .debug ({'msg' : 'logging initialized' }, 'debug' )
63
+
64
+
65
+ def log_level_from_environ ():
66
+ """Read the operator's desired log level from the LOG_LEVEL env var.
67
+
68
+ The log level string can be lowercase or uppercase. The string must be
69
+ one of the levels from the Python Standard Library's logging library.
70
+ Defaults to logging.INFO if the environment variable is not set.
71
+
72
+ Returns the logging.LEVEL object for the level that was read. Raises an
73
+ exception if the given log level is not one of the Python Standard
74
+ Library's log levels.
75
+ """
76
+ level_str = os .environ .get ('LOG_LEVEL' , 'INFO' )
77
+ # getattr() raises an exception if the requested log level doesn't exist.
78
+ return getattr (logging , level_str .upper ())
79
+
80
+
39
81
@click .command ()
40
82
@click .option ('--debug' , envvar = 'DEBUG' , is_flag = True )
41
83
@click .option ('--port' , envvar = 'PORT' , default = 8888 )
0 commit comments