Skip to content

Instantly share code, notes, and snippets.

@norsec0de
Created May 6, 2022 06:22
Show Gist options
  • Save norsec0de/6ae4c03f6c7fab68d1d2e2a915826530 to your computer and use it in GitHub Desktop.
Save norsec0de/6ae4c03f6c7fab68d1d2e2a915826530 to your computer and use it in GitHub Desktop.
Python - log to both console and file
import logging
# Global Configuration Variables
log_file = 'output.log'
# Configure Logging
log = logging.getLogger('logger')
log.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(message)s')
# Configure Logging to file with file handler = 'fh'
fh = logging.FileHandler(log_file, mode='w', encoding='utf-8')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
log.addHandler(fh)
# Configure Logging to console with console handler = 'ch'
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
log.addHandler(ch)
# Usage
log.debug('This is a debug log message')
log.info('This is an info log message')
log.warning('This is a warning log message')
log.error('This is an error log message')
log.critical('This is an error log message')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment