B. Cratty
B. Cratty

Reputation: 1991

Write to Logs in Python with Inline Message

Problem

I am developing lambda functions and in my code, I have multiple lines that look something along the lines like the following snippets.

logger = logging.getLogger()
logger.setLevel(logging.INFO)

#dummy example 1
logger.info("pre-formatted data")
logger.info(data)


#dummy example 2
logger.info("jsonData")
logger.info(json.dumps(jsonData)))

Question

I was hoping to do something along the lines of instead:

#desired output
logger.info("JSON Data", json.dumps(jsonData))

Upvotes: 0

Views: 671

Answers (1)

GalacticDessert
GalacticDessert

Reputation: 36

You can implement your own logger class in a way that behaves similarly to the default logger, but using *args to take an arbitrarily long number of parameters

See example:

import logging


class Logger:
    def __init__(self, name, level):
        logging.basicConfig(level=level)
        self._logger = logging.getLogger(name)

    def debug(self, *args):
        for arg in args:
            self._logger.debug(arg)

    def info(self, *args):
        for arg in args:
            self._logger.info(arg)

    def warning(self, *args):
        for arg in args:
            self._logger.warning(arg)

    def error(self, *args):
        for arg in args:
            self._logger.error(arg)


logger = Logger("test_logger", level=logging.INFO)
logger.info("logline1", "logline2", "logline3")

The output will be:

INFO:test_logger:logline1
INFO:test_logger:logline2
INFO:test_logger:logline3

Which can be adjusted by passing a format to the logging.basicConfig

Upvotes: 1

Related Questions