Skip to content

Instantly share code, notes, and snippets.

@ShaikeA
Last active January 13, 2019 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShaikeA/238166541bfe5815a4b47045ec37beef to your computer and use it in GitHub Desktop.
Save ShaikeA/238166541bfe5815a4b47045ec37beef to your computer and use it in GitHub Desktop.
import logging
class Logger:
def __init__(self):
# Initiating the logger object
self.logger = logging.getLogger(__name__)
# Set the level of the logger. This is SUPER USEFUL since it enables you to decide what to save in the logs file.
# Explanation regarding the logger levels can be found here - https://docs.python.org/3/howto/logging.html
self.logger.setLevel(logging.DEBUG)
# Create the logs.log file
handler = logging.FileHandler('logs.log')
# Format the logs structure so that every line would include the time, name, level name and log message
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# Adding the format handler
self.logger.addHandler(handler)
# And printing the logs to the console as well
self.logger.addHandler(logging.StreamHandler(sys.stdout))
# Usage example:
logger = Logger().logger
logger.debug("This log's level is 'DEBUG'")
logger.info("This log's level is 'info'")
logger.error("This log's level is 'error'")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment