Просмотр исходного кода

Make default logging more configurable

Alec Nikolas Reiter 7 лет назад
Родитель
Сommit
7e40520841
2 измененных файлов с 84 добавлено и 39 удалено
  1. 49 35
      flaskbb/app.py
  2. 35 4
      flaskbb/configs/default.py

+ 49 - 35
flaskbb/app.py

@@ -328,31 +328,60 @@ def configure_translations(app):
 
 def configure_logging(app):
     """Configures logging."""
+    if app.config.get('USE_DEFAULT_LOGGING'):
+        configure_default_logging(app)
 
-    logs_folder = os.path.join(app.root_path, os.pardir, "logs")
+    if app.config.get('LOG_CONF_FILE'):
+        logging.config.fileConfig(
+            app.config['LOG_CONF_FILE'], disable_existing_loggers=False
+        )
+
+    if app.config["SQLALCHEMY_ECHO"]:
+        # Ref: http://stackoverflow.com/a/8428546
+        @event.listens_for(Engine, "before_cursor_execute")
+        def before_cursor_execute(
+                conn, cursor, statement, parameters, context, executemany
+        ):
+            conn.info.setdefault('query_start_time', []).append(time.time())
+
+        @event.listens_for(Engine, "after_cursor_execute")
+        def after_cursor_execute(
+                conn, cursor, statement, parameters, context, executemany
+        ):
+            total = time.time() - conn.info['query_start_time'].pop(-1)
+            app.logger.debug("Total Time: %f", total)
+
+
+def configure_default_logging(app):
     from logging.handlers import SMTPHandler
+
+    logs_folder = app.config.get('LOG_PATH')
+
+    if logs_folder is None:
+        logs_folder = os.path.join(app.root_path, os.pardir, "logs")
+
+    default_log_format = '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
+
     formatter = logging.Formatter(
-        '%(asctime)s %(levelname)s: %(message)s '
-        '[in %(pathname)s:%(lineno)d]')
+        app.config.get('LOG_FORMAT') or default_log_format
+    )
 
     info_log = os.path.join(logs_folder, app.config['INFO_LOG'])
 
     info_file_handler = logging.handlers.RotatingFileHandler(
-        info_log,
-        maxBytes=100000,
-        backupCount=10
+        info_log, maxBytes=100000, backupCount=10
     )
 
-    info_file_handler.setLevel(logging.INFO)
+    log_level = app.config.get('LOG_LEVEL') or logging.INFO
+
+    info_file_handler.setLevel(log_level)
     info_file_handler.setFormatter(formatter)
     app.logger.addHandler(info_file_handler)
 
     error_log = os.path.join(logs_folder, app.config['ERROR_LOG'])
 
     error_file_handler = logging.handlers.RotatingFileHandler(
-        error_log,
-        maxBytes=100000,
-        backupCount=10
+        error_log, maxBytes=100000, backupCount=10
     )
 
     error_file_handler.setLevel(logging.ERROR)
@@ -360,34 +389,19 @@ def configure_logging(app):
     app.logger.addHandler(error_file_handler)
 
     if app.config["SEND_LOGS"]:
-        mail_handler = \
-            SMTPHandler(
-                app.config['MAIL_SERVER'],
-                app.config['MAIL_DEFAULT_SENDER'],
-                app.config['ADMINS'],
-                'application error, no admins specified',
-                (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
-            )
-
-        mail_handler.setLevel(logging.ERROR)
-        mail_handler.setFormatter(formatter)
-        app.logger.addHandler(mail_handler)
+        configure_mail_logs(app)
 
-    if app.config.get('LOG_CONF_FILE'):
-        logging.config.fileConfig(app.config['LOG_CONF_FILE'], disable_existing_loggers=False)
 
-    if app.config["SQLALCHEMY_ECHO"]:
-        # Ref: http://stackoverflow.com/a/8428546
-        @event.listens_for(Engine, "before_cursor_execute")
-        def before_cursor_execute(conn, cursor, statement,
-                                  parameters, context, executemany):
-            conn.info.setdefault('query_start_time', []).append(time.time())
+def configure_mail_logs(app):
+    mail_handler = SMTPHandler(
+        app.config['MAIL_SERVER'], app.config['MAIL_DEFAULT_SENDER'],
+        app.config['ADMINS'], 'application error, no admins specified',
+        (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
+    )
 
-        @event.listens_for(Engine, "after_cursor_execute")
-        def after_cursor_execute(conn, cursor, statement,
-                                 parameters, context, executemany):
-            total = time.time() - conn.info['query_start_time'].pop(-1)
-            app.logger.debug("Total Time: %f", total)
+    mail_handler.setLevel(logging.ERROR)
+    mail_handler.setFormatter(formatter)
+    app.logger.addHandler(mail_handler)
 
 
 def load_plugins(app):

+ 35 - 4
flaskbb/configs/default.py

@@ -47,15 +47,48 @@ class DefaultConfig(object):
     # This only affects the url generation with 'url_for'.
     PREFERRED_URL_SCHEME = "http"
 
+    # Logging Settings
+    # ------------------------------
+    # This config section will deal with the logging settings
+    # for FlaskBB, adjust as needed.
+
+    # Logging Config Path
+    # see https://docs.python.org/library/logging.config.html#logging.config.fileConfig
+    # for more details. Should either be None or a path to a file
+    # If this is set to a path, consider setting USE_DEFAULT_LOGGING to False
+    # otherwise there may be interactions between the log configuration file
+    # and the default logging setting.
+    #
+    # If set to a file path, this should be an absolute file path
+    LOG_CONF_FILE = None
+
+    # When set to True this will enable the default
+    # FlaskBB logging configuration which uses the settings
+    # below to determine logging
+    USE_DEFAULT_LOGGING = True
+
+    # Log format FlaskBB will use
+    LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
+
+    # Log level FlaskBB will use
+    LOG_LEVEL = "INFO"
+
     # If SEND_LOGS is set to True, the admins (see the mail configuration) will
     # recieve the error logs per email.
     SEND_LOGS = False
 
-    # The filename for the info and error logs. The logfiles are stored at
-    # flaskbb/logs
+    # Path to store the INFO and ERROR logs
+    # If None this defaults to flaskbb/logs
+    #
+    # If set to a file path, this should be an absolute path
+    LOG_PATH = None
+
+    # The filename for the info and error logs. The logfiles are stored
+    # at the path specified in LOG_PATH
     INFO_LOG = "info.log"
     ERROR_LOG = "error.log"
 
+
     # Database
     # ------------------------------
     # For PostgresSQL:
@@ -192,8 +225,6 @@ class DefaultConfig(object):
     AUTH_URL_PREFIX = "/auth"
     ADMIN_URL_PREFIX = "/admin"
 
-    # Logging Config Path
-    LOG_CONF_FILE = None
 
     # Plugin Folder
     PLUGINS_FOLDER = os.path.join(basedir, "flaskbb", "plugins")