Last active
August 29, 2015 14:03
-
-
Save tkrajina/da73a6d0dbaea7d01294 to your computer and use it in GitHub Desktop.
Setup logging
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 | |
import os.path as path | |
def setup_logging(file_name, log_directory=None, stream=None, max_bytes=None, | |
backup_count=None): | |
""" | |
Log directory may be a file in that directory. | |
""" | |
f = logging.Formatter(fmt='%(levelname)s:%(name)s: %(message)s ' | |
'(%(asctime)s; %(filename)s:%(lineno)d)', | |
datefmt="%Y-%m-%d %H:%M:%S") | |
if log_directory and not path.isdir(log_directory): | |
if path.sep in log_directory: | |
log_directory = path.dirname(log_directory)[0 : log_directory.rindex(path.sep)] | |
else: | |
log_directory = '' | |
if not log_directory: | |
log_directory = '' | |
file_name = path.join(log_directory, file_name) | |
if not max_bytes: | |
max_bytes = 100000 | |
if not backup_count: | |
backup_count = 10 | |
handlers = [ | |
logging.handlers.RotatingFileHandler(file_name, encoding='utf8', maxBytes=max_bytes, | |
backupCount=backup_count), | |
] | |
if stream: | |
handlers.append(logging.StreamHandler()) | |
root_logger = logging.getLogger() | |
root_logger.setLevel(logging.DEBUG) | |
for h in handlers: | |
h.setFormatter(f) | |
h.setLevel(logging.DEBUG) | |
root_logger.addHandler(h) | |
logging.info('Logging setup done') | |
if __name__ == '__main__': | |
setup_logging('rotated.log', stream=True) | |
logger = logging.getLogger(__name__) | |
logging.info('logging.info') | |
logger.info('test') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment