Python Logging Formatter

April 25, 2019
Remove miliseconds, show time only, show function name, show logger name

Custom Logger Formatter

log = logging.getLogger(__name__)

log.setLevel(logging.DEBUG)
formatter = logging.Formatter(fmt="%(asctime)s %(levelname)s %(module)s: %(message)s",
                          datefmt="%H:%M:%S")
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)

# log.propagate = False
log.addHandler(handler)

Sample output

12:52:03 INFO [module]: [message]

Root Logger Formatter

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format="%(asctime)s %(levelname)s %(module)s: %(message)s", datefmt="%H:%M:%S")

or

logger = logging.getLogger()
log.setLevel(logging.DEBUG)
formatter = logging.Formatter(fmt="%(asctime)s %(levelname)s %(module)s: %(message)s",
                          datefmt="%H:%M:%S")
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)

# log.propagate = False
log.addHandler(handler)

Attributes

List of attributes

Show Full DateTime with miliseconds

formatter = logging.Formatter(fmt="%(asctime)s %(levelname)s %(module)s: %(message)s")
2019-04-25 13:11:33,523 INFO [module]: [message]

Show DateTime without miliseconds

formatter = logging.Formatter(fmt="%(asctime)s %(levelname)s %(module)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
2019-04-25 13:11:33 INFO [module]: [message]

Show Function Name

formatter = logging.Formatter(fmt="%(asctime)s %(levelname)s %(module)s: %(funcName)s : %(message)s")
2019-04-25 13:11:33,523 INFO [module]: [funcName] : [message]

Show Logger Name

formatter = logging.Formatter(fmt="%(asctime)s %(levelname)s %(name)s: %(module)s : %(message)s")
2019-04-25 13:11:33,523 INFO [loggerName]: [module]: [message]
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.