我编写了以下代码,编码人员需要在代码中决定在日志文件或控制台中显示和保存日志o / p的位置,这也是必要条件。接受一个全局变量,编码器将提及类型(文件或控制台),并将其传递给具有if和else条件的函数。代码可以正常工作,但是我不确定这是否是正确有效的方法做这个。我已经使用了Python的Logging库。让我知道您的宝贵建议,以下是代码:
# define the levels of events here and format of messages
logformt = "Date/Time: %(asctime)s,Error Msg: %(message)s"
loglevl = logging.ERROR
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -
%(message)s')
gethandler = 'file'
# Function to take input from the command line interface
logger = logging.getLogger()
def decidehanlder(value):
if value == 'console':
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(loglevl)
# create formatter and add it to the handlers
ch.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
elif value == 'file':
# create file handler which logs messages
fh = logging.FileHandler('spam.log')
fh.setLevel(loglevl)
# create formatter and add it to the handlers
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(fh)
if __name__ == '__main__':
#filenam = inpfil()
def main(filenam):
decidehanlder(gethandler)