-
Notifications
You must be signed in to change notification settings - Fork 0
Python Logging
Heath Brown edited this page Jan 24, 2024
·
5 revisions
import logging.config
logger.getLogger("my_app")
logging_config = {
"version": 1,
"disable_existing_loggers" : False,
"filters" : {},
"formatteres" : {},
"handlers" : {},
"loggers" : {}
}
def main():
logging.config.dictConfig(config=logging_config)
...
#mocding example see youtube link above
logging.info("uses root logger") #BAD
logger = logging.getLogger("myapp") # User your own logger, Good
- don't getLogger(name) in every file
- https://youtu.be/9L77QExPmI0?t=461
Tip #5 from MCoding: Instead of inside the Python application as a dict you can read in configuration from file
- Store as JSON or YAML
- Parse configuration
Example: config.json
{
"version": 1,
"disable_existing_loggers" : False,
"formatteres" : {
"simple" : {
"format" : "%(levelname)s: %(message)s",
}
},
"handlers" : {
"stdout": {
"class": "logging.StreamHandler",
"formatter": "simple",
"stream": "ext://sys.stdout",
}
},
"loggers" : {
"root": {"level": "DEBUG", "handlers": ["stdout"]}
}
}
- https://youtu.be/9L77QExPmI0?t=772
- Write a custom Handler that generates JSON strings
logging_config = {
"version": 1,
"disable_existing_loggers" : False,
"formatteres" : {
"simple" : {
"format" : "%(levelname)s: %(message)s",
}
},
"handlers" : {
"stdout": {
"class": "logging.StreamHandler",
"formatter": "simple",
"stream": "ext://sys.stdout",
}
},
"loggers" : {
"root": {"level": "DEBUG", "handlers": ["stdout"]}
}
}
should not have configuration You can have logging and handlers but no 'configuration'
- Don't log user input (avoid makeLogRecord)
- If you do NEED to sanitize the input before logging
- DO NOT send python objects to logging as pickle