Skip to content

Instantly share code, notes, and snippets.

@shapiromatron
Created February 19, 2020 16:49
Show Gist options
  • Select an option

  • Save shapiromatron/fd9949379555c54e0c765c103effc1ea to your computer and use it in GitHub Desktop.

Select an option

Save shapiromatron/fd9949379555c54e0c765c103effc1ea to your computer and use it in GitHub Desktop.
simple-logging

Simple python logging

This gist demonstrates how to setup logging and write to both standard-error and a file.

Output is printed to stderr as well as a file. For example:

$ python logger.py 
2020-02-19 11:46:59,473: WARNING: __main__: Starting to do stuff...
2020-02-19 11:47:01,480: INFO: __main__: Stuff done!
$ cat my-log.log 
2020-02-19 11:45:34,918 - __main__ - WARNING - Starting to do stuff...
2020-02-19 11:45:36,920 - __main__ - INFO - Stuff done!
import logging
import time
def main():
# get the logger based on the filename; this tells you where the log is coming form
logger = logging.getLogger(__name__)
logger.warning("Starting to do stuff...")
time.sleep(2)
logger.info("Stuff done!")
if __name__ == "__main__":
# you setup configuration at the main entrypoint to the code
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s: %(levelname)s: %(name)s: %(message)s",
handlers=[logging.FileHandler("my-log.log"), logging.StreamHandler()],
)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment