Created
May 6, 2022 06:22
-
-
Save norsec0de/6ae4c03f6c7fab68d1d2e2a915826530 to your computer and use it in GitHub Desktop.
Python - log to both console and file
This file contains 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 | |
# 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