I am new to python, and developing a moderate application for which I need to setup a logging mechanism.
The below program sets up log handling, which gives the user an option to specify whether log rotation is required or not.
The rest is my application. The code is mostly written in terms of functions (not using classes) which are irrelevant to the log setup and mostly contain printing log messages.
But before going ahead with the complete application, I would like to know from experts whether the following approach of using RotatingFileHandler
and basicConfig
is good enough.
I would like to know the comments for below:
- In case if I want to filter logs (either to stdout or file) based on log levels.
- Adding any new handlers
- Any other unforeseen problems (I am just a fresh learner)
- In general is this the correct approach for supporting
RotatingFileHandler
andbasicConfig
- Any other general comments
import logging
import logging.handlers
try:
import configparser
except ImportError:
# Python 2.x fallback
import ConfigParser as configparser
import argparse
LOG_FILENAME = 'debug.log'
LOG_PATH = "C:\\tool_temp\\"
# Set up a specific logger with our desired output level
logger = logging.getLogger('MYAPP')
def log_setup(dir_name, config_dict):
is_log_enabled = config_dict['logrotate_k']
if is_log_enabled == "enabled":
print "logrotation enabled"
# Add the log message rotate_handler to the logger
rotate_handler = logging.handlers.RotatingFileHandler(dir_name+LOG_FILENAME, maxBytes=512, backupCount=5)
#'%b %d %H:%M:%S' is to avoid printing 628 after 2021-05-25 16:30:30,628
formatter = logging.Formatter('%(asctime)s : %(levelname)s: %(filename)s::%(funcName)s:%(lineno)d %(message)s', '%d %b %d %H:%M:%S')
rotate_handler.setFormatter(formatter)
logger.addHandler(rotate_handler)
logger.setLevel(logging.DEBUG)
else:
print "logrotation is disabled"
date_strftime_format = "%d %b %y %H:%M:%S"
message_format='%(asctime)s : %(levelname)s %(filename)s:: %(funcName)s:%(lineno)d %(message)s'
#by default, the logging module logs the messages with a severity level of WARNING or above. so used level=logging.DEBUG
# to log everything from debug to critical
logging.basicConfig(filename = dir_name+LOG_FILENAME, format = message_format, datefmt = date_strftime_format,level=logging.DEBUG)
def is_file_exist(config_file_path):
if os.path.exists(config_file_path):
return True
else:
return False
#Reading config file through sections and keys
def read_config(cfg_path):
config_dict = {}
config = configparser.ConfigParser()
try:
config.read(cfg_path)
config_dict['logrotate_k'] = config.get('CONF_PARAMS', 'logrotate')
except Exception as e:
print("Error",str(e))
sys.exit()
return config_dict
# For parsing the command line arguments
# returns dictionary "config_dict" with the app build parameters
def parse_command_line_args():
config_dict = {}
parser = argparse.ArgumentParser(description='My Application')
parser.add_argument('-config_file', type = str)
parser.add_argument('-logrotate',type=str,help='logrotation enabled or not')
input_args = parser.parse_args()
config_file_path = input_args.config_file
if config_file_path != None:
if is_file_exist(config_file_path) == True:
print "Reading configs from config file: " + config_file_path
config_dict = read_config(config_file_path)
else:
print config_file_path + " does not exists"
sys.exit()
else:
print "reading configs from command line"
config_dict['logrotate_k'] = input_args.logrotate
return config_dict
if __name__ == "__main__":
config_dict = {}
config_dict = parse_command_line_args()
log_setup(LOG_PATH+LOG_FILENAME,config_dict)
logger.info('this info is from main')
logger.error('this is test error message from main')
print config_dict