''' # Copyright (C) 2005-2021 Splunk Inc. All Rights Reserved. ''' import logging try: from splunk.clilib.bundle_paths import make_splunkhome_path except ImportError: from splunk.appserver.mrsparkle.lib.util import make_splunkhome_path DEFAULT_FORMAT = '%(asctime)s %(levelname)s pid=%(process)d tid=%(threadName)s file=%(filename)s:%(funcName)s:%(lineno)d | %(message)s' SHORT_FORMAT = '%(asctime)s %(levelname)s %(message)s' def setup_logger(name, level=logging.WARNING, maxBytes=25000000, backupCount=5, format=DEFAULT_FORMAT): ''' Set up a default logger. @param name: The log file name. @param level: The logging level. @param maxBytes: The maximum log file size before rollover. @param backupCount: The number of log files to retain. ''' # Strip ".py" from the log file name if auto-generated by a script. if '.py' in name: name = name.replace(".py", "") logfile = make_splunkhome_path(["var", "log", "splunk", name + '.log']) # Set the level here, otherwise subsequent calls to getLogger seem to lose the level setting. logging.basicConfig(level=level) logger = logging.getLogger(name) logger.propagate = False # Prevent the log messages from being duplicated in the python.log file # Prevent re-adding handlers to the logger object, which can cause duplicate # log lines. handler_exists = any([True for h in logger.handlers if h.baseFilename == logfile]) if not handler_exists: file_handler = logging.handlers.RotatingFileHandler(logfile, mode='a', maxBytes=maxBytes, backupCount=backupCount) formatter = logging.Formatter(format) file_handler.setFormatter(formatter) logger.addHandler(file_handler) return logger