Last active
March 26, 2022 23:30
-
-
Save gesquive/8815292 to your computer and use it in GitHub Desktop.
Code snippet to setup logger in python
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 | |
import logging.handlers | |
LOG_FILE = 'path/to/logfile' | |
LOG_SIZE = 1024*1024*200 | |
LOG_COUNT = 9 | |
log_file = LOG_FILE | |
dir_path = os.path.dirname(log_file) | |
if os.access(dir_path, os.W_OK): | |
file_handler = logging.handlers.RotatingFileHandler(log_file, | |
maxBytes=LOG_SIZE, | |
backupCount=LOG_COUNT) | |
file_formater = logging.Formatter('%(asctime)s,%(levelname)s,%(process)d,%(message)s', | |
"%Y-%m-%d %H:%M:%S") | |
file_handler.setFormatter(file_formater) | |
logging.getLogger('').addHandler(file_handler) | |
if verbose: | |
console_handler = logging.StreamHandler(sys.stdout) | |
console_formatter = logging.Formatter("[%(asctime)s] %(levelname)-5.5s: %(message)s", | |
"%Y-%m-%d %H:%M:%S") | |
console_handler.setFormatter(console_formatter) | |
logging.getLogger('').addHandler(console_handler) | |
# Add a null handler in case we don't have a log file and verbose isn't triggered | |
logging.getLogger('').addHandler(logging.NullHandler()) | |
logging.getLogger('').setLevel(logging.DEBUG) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment