samba/logger: add logger module for python
authorJoe Guo <joeg@catalyst.net.nz>
Mon, 20 Aug 2018 22:48:04 +0000 (10:48 +1200)
committerDouglas Bagnall <dbagnall@samba.org>
Wed, 10 Oct 2018 04:16:21 +0000 (06:16 +0200)
We need a consitent way for logging in Samba Python code.

This module provides a factory method `get_samba_logger` to create logger,
with a reasonable default format and optional color.

Signed-off-by: Joe Guo <joeg@catalyst.net.nz>
Reviewed-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
Reviewed-by: Andrew Bartlett <abartlet@samba.org>
python/samba/logger.py [new file with mode: 0644]

diff --git a/python/samba/logger.py b/python/samba/logger.py
new file mode 100644 (file)
index 0000000..a3db3be
--- /dev/null
@@ -0,0 +1,66 @@
+# Samba common functions
+#
+# Copyright (C) Joe Guo <joeg@catalyst.net.nz>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+
+import sys
+import logging
+from samba.colour import GREY, YELLOW, GREEN, RED, DARK_RED, C_NORMAL
+
+LEVEL_COLORS = {
+    logging.CRITICAL: DARK_RED,
+    logging.ERROR: RED,
+    logging.WARNING: YELLOW,
+    logging.INFO: GREEN,
+    logging.DEBUG: GREY,
+}
+
+
+class ColoredFormatter(logging.Formatter):
+    """Add color to log according to level"""
+
+    def format(self, record):
+        log = super(ColoredFormatter, self).format(record)
+        color = LEVEL_COLORS.get(record.levelno, GREY)
+        return color + log + C_NORMAL
+
+
+def get_samba_logger(
+        name='samba', stream=sys.stderr, use_color=True,
+        level=None, verbose=False, quiet=False,
+        fmt=('%(levelname)s %(asctime)s pid:%(process)d '
+             '%(pathname)s #%(lineno)d: %(message)s'),
+        datefmt=None):
+    """
+    Get a logger instance and config it.
+    """
+    logger = logging.getLogger(name)
+
+    if not level:
+        # if level not specified, map options to level
+        level = ((verbose and logging.DEBUG) or
+                 (quiet and logging.WARNING) or logging.INFO)
+
+    logger.setLevel(level)
+
+    Formatter = use_color and ColoredFormatter or logging.Formatter
+    formatter = Formatter(fmt=fmt, datefmt=datefmt)
+
+    handler = logging.StreamHandler(stream=stream)
+    handler.setFormatter(formatter)
+    logger.addHandler(handler)
+
+    return logger