Pages

Saturday, June 9, 2012

Python: How i implemented logging in my tool

#How I implemented logging in my tool:
#Requirement is to create a log file which has the name of BATCH JOB being executed, The environment being tested and The Date and Time information as the tool can be executed multiple times back to back
# INPUT_FILE_NAME is passed as second argument to the batch job
#  TEST_ENVIRONMENT is passed as third argument to the batch job

import time
import sys
import os
import datetime
import logging

# Split the input file name and take the first part of the name i.e. except .extension
log_file_name = 'logfile_' + os.path.splitext(str(sys.argv[1]))[0] + '_' + str(sys.argv[2]) + '_' + str(datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")) + '.log'

logger = logging.getLogger('Testing_Automation_Advanced')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler(log_file_name)
# LOG everything to the log file i.e. at DEBUG level
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
# Show only INFO+ level on the standard output i.e. screen
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
fhformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
chformatter = logging.Formatter('%(asctime)s - %(message)s')
ch.setFormatter(chformatter)
fh.setFormatter(fhformatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

#USE
logger.debug ('Logging at DEBUG level')
logger.info('Logging at INFO level')

# You can also encapsulate the logging directly and implement some STYLEs e.g.

def Print_Log_Style(log_text, style=None):
'''Puts the provided text in the list for the log file and also prints
it on the screen'''

if style.strip().upper() == 'TITLE':
multiplier = int(30-(len(log_text)/2))
logger.debug(60*'*')
logger.debug(' '*multiplier + log_text)
logger.debug(60*'*')

if style.strip().upper() == 'HEADER':
multiplier = int(15-(len(log_text)/2))
logger.debug(30*'-')
logger.debug(' '*multiplier + log_text)
logger.debug(30*'-')
if style.strip().upper() == 'SECTION':
multiplier = int(15-(len(log_text)/2))
logger.debug(30*'=')
logger.debug(' '*multiplier + log_text)
logger.debug(30*'=')
if style.strip().upper() is None:
logger.debug(log_text)

No comments:

Post a Comment

Please write your comments and suggestions