Beispiel #1
0
    def test_014_file_json_object(self):
        """
        Remove log and test default formatting
        """
        rmlog()
        fileSpecs = [{
            "filename": LOGFILE,
            "level": logging.DEBUG,
            "format": "json"
        }]
        termSpecs = {
            "color": True,
            "splitLines": True,
            "level": logging.WARNING
        }
        Logger.init(LOGDIR, termSpecs=termSpecs, fileSpecs=fileSpecs)

        logging.debug(["hello", "world"], extra={"when": "today"})

        with open(LOGPATH) as f:
            cont = json.loads(f.read())

        self.assertEqual(True, "object" in cont, msg="Got: %s" % str(cont))
        self.assertEqual(["hello", "world"],
                         cont["object"],
                         msg="Got: %s" % str(cont))
Beispiel #2
0
 def test_016_file_defaults(self):
     """
     Test default logging level for file
     """
     rmlog()
     Logger.addFileLogger({"filename": LOGFILE})
     self.assertEqual(logging.INFO, logging.getLogger().handlers[1].level)
Beispiel #3
0
def main():
    global result
    parser = argparse.ArgumentParser(
        usage="%(prog)s [options]\n\n\tTest lazylog")
    parser.add_argument('-t',
                        '--tests',
                        nargs="*",
                        required=False,
                        help="Run specific tests (multiple can be specified)")
    parser.add_argument('-d',
                        '--debug',
                        required=False,
                        help="Enable DEBUG Logging",
                        action='store_true')
    parser.add_argument('-v',
                        '--verbosity',
                        type=int,
                        required=False,
                        help="Verbosity level (test suite), default 1",
                        default=1)
    args = parser.parse_args()

    # Setup Logging
    #fileSpecs = [{"filename": log_file, "level":lg.DEBUG}]
    termSpecs = {"color": True, "splitLines": True, "level": lg.DEBUG}
    if not args.debug:
        termSpecs["level"] = lg.WARNING

    Logger.init(LOGDIR, termSpecs=termSpecs, fileSpecs=None)
    lg.getLogger("tests").setLevel(level=lg.DEBUG)

    if not args.tests:
        suite = unittest.TestLoader().discover(ROOTDIR + '/tests')
    else:
        lg.info(' * Running specific tests')

        suite = unittest.TestSuite()

        # Load standard tests
        for t in args.tests:
            # Remove folder name if there
            t = re.sub(r".*tests/", "", t)
            t = re.sub(r"\.py$", "", t)
            test = unittest.TestLoader().loadTestsFromName("tests." + t)
            suite.addTest(test)

    # Run
    lg.info("Single threaded tests")
    result = unittest.TextTestRunner(verbosity=args.verbosity).run(suite)
    result = result.wasSuccessful()

    if result is False:
        lg.info("Failing tests...")
        return 1

    lg.info("Success!")
    return 0
Beispiel #4
0
 def test_015_file_misconfig(self):
     """
     Test misconfiguration
     """
     rmlog()
     with self.assertRaises(RuntimeError):
         Logger.addFileLogger({
             "filename_": LOGFILE,
             "level": logging.DEBUG,
             "format": "json"
         })
Beispiel #5
0
    def test_006_pretty_true_split_false(self):
        """
        Get a new logger and ...
        """
        # Reset Logger
        termSpecs = {
            "color": True,
            "splitLines": False,
            "level": logging.DEBUG,
            "pretty": True,
        }
        Logger.init(LOGDIR, termSpecs=termSpecs, fileSpecs=None)

        strio = logging.getLoggerClass().mockHandler(0)
        logging.debug("Hello\nWorld")
        logging.getLoggerClass().restoreHandler(0)

        self.assertEqual(2, len(strio.getvalue().splitlines()))
Beispiel #6
0
    def test_003_pretty_false_split_true(self):
        """
        Get a new logger and ...
        """
        # Reset Logger
        termSpecs = {
            "color": True,
            "splitLines": True,
            "level": logging.DEBUG,
            "pretty": False,
        }
        Logger.init(LOGDIR, termSpecs=termSpecs, fileSpecs=None)

        strio = logging.getLoggerClass().mockHandler(0)
        logging.debug({"hello": 1, "world": 2})
        logging.getLoggerClass().restoreHandler(0)

        # We expect 1 line in default mode
        self.assertEqual(1, len(strio.getvalue().splitlines()))
Beispiel #7
0
    def test_007_file_default_implied(self):
        """
        Remove log and test console-like formatting
        """
        rmlog()
        fileSpecs = [{"filename": LOGFILE, "level": logging.DEBUG}]
        termSpecs = {
            "color": True,
            "splitLines": True,
            "level": logging.WARNING
        }
        Logger.init(LOGDIR, termSpecs=termSpecs, fileSpecs=fileSpecs)

        logging.debug({"hello": 1, "world": 2})

        with open(LOGPATH) as f:
            cont = f.read()

        self.assertEqual(1, len(cont.splitlines()))
Beispiel #8
0
    def test_017_console_fmt(self):
        """
        Test formats
        """
        termSpecs = {"color": False}
        Logger.init(LOGDIR,
                    fmt='%(asctime)s %(levelname)-8s %(lineno)s: %(message)s',
                    datefmt="%Y",
                    termSpecs=termSpecs)

        strio = logging.getLoggerClass().mockHandler(0)
        logging.debug("hmmm")
        # Now, put it back!
        logging.getLoggerClass().restoreHandler(0)

        now = datetime.datetime.now()
        expect = "%s DEBUG" % now.year
        self.assertTrue(strio.getvalue().startswith(expect),
                        msg="Got: %s, expected: %s" %
                        (strio.getvalue(), expect))
Beispiel #9
0
    def test_010_file_default(self):
        """
        Remove log and test default formatting
        """
        rmlog()
        fileSpecs = [{
            "filename": LOGFILE,
            "level": logging.DEBUG,
            "format": "default"
        }]
        termSpecs = {
            "color": True,
            "splitLines": True,
            "level": logging.WARNING
        }
        Logger.init(LOGDIR, termSpecs=termSpecs, fileSpecs=fileSpecs)

        logging.debug({"hello": 1, "world": 2})

        with open(LOGPATH) as f:
            cont = f.read()

        self.assertEqual(1, len(cont.splitlines()), msg="Got: %s" % cont)
Beispiel #10
0
    def test_018_set_levels(self):
        """
        Test default logging level for file
        """
        rmlog()
        fileSpecs = [{
            "filename": LOGFILE,
            "level": logging.DEBUG,
            "format": "json"
        }]
        termSpecs = {
            "color": True,
            "splitLines": True,
            "level": logging.WARNING
        }
        Logger.init(LOGDIR, termSpecs=termSpecs, fileSpecs=fileSpecs)

        Logger.setConsoleLevel(logging.DEBUG)
        Logger.setFileLevel(1, logging.WARNING)

        self.assertEqual(logging.DEBUG, logging.getLogger().handlers[0].level)
        self.assertEqual(logging.WARNING,
                         logging.getLogger().handlers[1].level)
Beispiel #11
0
#!/usr/bin/env python3
import os
import sys
import tempfile
import logging

# Set the paths
LOGDIR = tempfile.gettempdir()
ROOTDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(ROOTDIR)

from lazylog import Logger

# Console only logger
termSpecs = {"level": logging.DEBUG, "splitLines": False, "pretty": False }
Logger.init(LOGDIR, termSpecs=termSpecs)

logging.debug("You can remove all the fancy stuff:")
logging.info("... keeping\n each message\n in its own line")
logging.warning({"and": "flatten structures", "like": list("lists")})

logging.info("RECONFIGURING....")
termSpecs = {"level": logging.DEBUG, "splitLines": True, "pretty": False }
Logger.init(LOGDIR, termSpecs=termSpecs)
logging.error("However,\nYou can choose to split\nlines")
logging.critical(["but", "not", "prettify\nstructs"])

logging.info("RECONFIGURING....")
termSpecs = {"level": logging.DEBUG, "splitLines": False, "pretty": False, "color": False }
Logger.init(LOGDIR, termSpecs=termSpecs)
logging.info("Boooriiiing")
Beispiel #12
0
LOGDIR = tempfile.gettempdir()
LOGFILE = "simple-log-examples.log"
LOGFILE2 = "simple-log-examples-2.log"
LOGPATH = "%s/%s" % (LOGDIR, LOGFILE)
LOGPATH2 = "%s/%s" % (LOGDIR, LOGFILE2)
ROOTDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(ROOTDIR)

from lazylog import Logger

#
# 1. Default file log
#
termSpecs = {"level": logging.DEBUG}
fileSpecs = [{"filename": LOGFILE, "level": logging.DEBUG}]
Logger.init(LOGDIR, termSpecs=termSpecs, fileSpecs=fileSpecs)

logging.debug("^---same as console, this is an example log line")
logging.info("This logger handles\nNew\nLines")
logging.warning({"but": "Flattens structs by default"})
logging.error("Errors DONT stick out - color is not used")

print("\nFile Contents:\n")
with open(LOGPATH) as f:
    print(f.read())

os.unlink(LOGPATH)

#
# 2. Customizing: Not splitting new lines
#
Beispiel #13
0
 def setUp(cls):
     termSpecs = {"color": True, "splitLines": True, "level": logging.DEBUG}
     Logger.init(LOGDIR, termSpecs=termSpecs)
Beispiel #14
0
#!/usr/bin/env python3
import os
import sys
import tempfile
import logging

# Set the paths
LOGDIR = tempfile.gettempdir()
ROOTDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(ROOTDIR)

from lazylog import Logger

# Console only logger
Logger.init()

logging.debug("This is an example log line")
logging.info("This logger handles\nNew\nLines")
logging.warning({
    "also": "handles basic structures",
    "like": list("lists"),
    "and": ("colors", "!")
})
logging.error("Errors stick out")
logging.critical("but critical sticks out more...")