Skip to main content
Tweeted twitter.com/StackCodeReview/status/1397341766823596034
Became Hot Network Question
deleted 4 characters in body
Source Link
Reinderien
  • 71.2k
  • 5
  • 76
  • 257

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 logrotationlog rotation is required or not.

Rest allThe rest is my application. The code is mostly written in terms of functions (not using classes) and which isare irrelevant to the log setup and mostly containscontain printing log messages.

  1. In case if I want to filter logs  (either to stdout or file) based on log levels.
  2. Adding any new handlers
  3. Any other unforeseen problems ( II am just a fresh learner)
  4. In general is this the correct approach for supporting RotatingFileHandler and basicConfig
  5. Any other general comments

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 logrotation is required or not.

Rest all is my application. The code is mostly written in terms of functions (not using classes) and which is irrelevant to the log setup and mostly contains printing log messages.

  1. In case if I want to filter logs(either to stdout or file) based on log levels.
  2. Adding any new handlers
  3. Any other unforeseen problems ( I am just a fresh learner)
  4. In general is this the correct approach for supporting RotatingFileHandler and basicConfig
  5. Any other general comments

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.

  1. In case if I want to filter logs  (either to stdout or file) based on log levels.
  2. Adding any new handlers
  3. Any other unforeseen problems (I am just a fresh learner)
  4. In general is this the correct approach for supporting RotatingFileHandler and basicConfig
  5. Any other general comments
remove thanks - say thanks by voting on answers; added tag, fix spelling, update wording
Source Link

I am new to python, and developing a moderate application for which, I need to setup a logging mechanism. Below

The below program sets up log handling, which gives the user an option to specify whether logrotaionlogrotation is required or not.

Rest all is my application , the. The code is mostly written in terms of functions (not using classes) and which is irrelaventirrelevant to the log setup and mostly contains 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.

Thanks in advance.

I am new to python, and developing a moderate application for which, I need to setup a logging mechanism. Below program sets up log handling which gives user an option to specify whether logrotaion is required or not.

Rest all is my application , the code is mostly written in terms of functions (not using classes) and which is irrelavent to the log setup and mostly contains printing log messages.

But before going ahead with the complete application, I would like to know from experts whether following approach of using RotatingFileHandler and basicConfig is good enough.

Thanks in advance.

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 logrotation is required or not.

Rest all is my application. The code is mostly written in terms of functions (not using classes) and which is irrelevant to the log setup and mostly contains 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.

Source Link
Cheppy
  • 83
  • 1
  • 4

log setup using RotatingFileHandler and basicConfig

I am new to python, and developing a moderate application for which, I need to setup a logging mechanism. Below program sets up log handling which gives user an option to specify whether logrotaion is required or not.

Rest all is my application , the code is mostly written in terms of functions (not using classes) and which is irrelavent to the log setup and mostly contains printing log messages.

But before going ahead with the complete application, I would like to know from experts whether following approach of using RotatingFileHandler and basicConfig is good enough.

I would like to know the comments for below:

  1. In case if I want to filter logs(either to stdout or file) based on log levels.
  2. Adding any new handlers
  3. Any other unforeseen problems ( I am just a fresh learner)
  4. In general is this the correct approach for supporting RotatingFileHandler and basicConfig
  5. Any other general comments

Thanks in advance.

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