Python Logging Formatter

Apr 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 = Falselog.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 = Falselog.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]

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.