Last active
June 7, 2024 09:24
-
-
Save suiluj/cc9b5d5f452044c320a092969549c24c to your computer and use it in GitHub Desktop.
python logging pretty print pformat indent width line break
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import time | |
from pprint import pformat | |
# pretty print logs: https://stackoverflow.com/a/11093247/5628238 | |
# pformat indent: https://stackoverflow.com/a/29469358/5628238 | |
# (even needed when using %s string format): do not evaluate complex pformat when log level not printed: https://docs.python.org/3/library/logging.html#logging.Logger.isEnabledFor | |
# (wrong: complex variable string takes time nevertheless): https://reinout.vanrees.org/weblog/2015/06/05/logging-formatting.html | |
# https://stackoverflow.com/questions/13131400/logging-variable-data-with-new-format-string | |
# main script or module | |
import logging | |
logging.basicConfig(format='%(name)s:%(levelname)s:%(message)s') # do not set global level, because otherwise everything gets logged | |
logger = logging.getLogger(__name__) # get logger with name of current module (gets value __main__ for main script) | |
# logger_module_xy = logging.getLogger('<module_name>') # get logger of current module | |
logger.setLevel(logging.DEBUG) | |
# logger_module_xy.setLevel(logging.INFO) # (for example) | |
# | |
# | |
logger.debug('Hi') | |
# | |
# | |
logger.setLevel(logging.INFO) | |
def get_complex_log_message(): | |
time.sleep(3) | |
return {"object_after": "three seconds"} | |
start_time = time.time() | |
logger.info("Start time: %s", start_time) | |
logger.debug("%s",get_complex_log_message()) # this part takes 3 seconds even when it is not printed | |
end_time = time.time() | |
logger.info("End time: %s", end_time) | |
logger.info("--- It took %s seconds ---", (end_time - start_time)) | |
# thats why it is a good idea to encapsulate pformat strings for complex objects in this if clause: | |
complex_object = {"x": {"xx": 11, "xy": 12},"y": 2,"z": 3} | |
if logger.isEnabledFor(logging.DEBUG): | |
logger.info('this gets only evaluated when logging level is set to debug even when this is set to info') | |
# this more complex logging command width pformat is only evaluated when logging level is set to debug | |
# print pretty formated string in new line for better readability, | |
# width=1 forces linebreaks, width=30 forces less linebreaks and so on | |
logger.debug("\n%s",pformat(complex_object,indent=1,width=1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment