简体   繁体   中英

Refining the logging method in python tornado

I am trying to log the actions in a function and I have written the following function to log responses to different files based on the type of response ie info,error,debug and warning.

logging.basicConfig(filename='indivi_service.log',
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' )
def setup_logger(logger_name, log_file, level=logging.DEBUG):
    l = logging.getLogger(logger_name)
    formatter = logging.Formatter()
    fileHandler = logging.FileHandler(log_file)
    fileHandler.setFormatter(formatter)
    handler = TimedRotatingFileHandler(logger_name,
                               when="d",
                               interval=1,
                               backupCount=100)


l.setLevel(level)
l.addHandler(fileHandler)
l.addHandler(handler)


setup_logger('debug', r'debug')
setup_logger('error', r'error')
setup_logger('warning', r'warning')
setup_logger('info', r'info')
debug = logging.getLogger('debug')
error = logging.getLogger('error')
warning = logging.getLogger('warning')
info = logging.getLogger('info')


class Info(APIHandler):
    @gen.coroutine
    def post(self):
        req = json.loads(self.request.body)
        resp, content = client(item_id=req['item_id'])
        debug.debug(content)
        info.info(hello world)
        warning.warn('warning message')
        error.error('error message')

The problem that I am facing is that a response is printed twice each time I call a function.

for example: info.log

hello world hello world

Can anyone tell me why is it happening like. This is the case with all the log files.

Thanks

try:

import logging
import logging.handlers

logging.basicConfig(filename='indivi_service.log',
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' )
def setup_logger(logger_name, log_file, level=logging.DEBUG):
    l = logging.getLogger(logger_name)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler = logging.handlers.TimedRotatingFileHandler(str(log_file)+'.log', when="d", interval=1, backupCount=100)
    handler.setFormatter(formatter)

    l.setLevel(level)
    l.addHandler(handler)


setup_logger('debug', r'debug')
setup_logger('error', r'error')
setup_logger('warning', r'warning')
setup_logger('info', r'info')
debug = logging.getLogger('debug')
error = logging.getLogger('error')
warning = logging.getLogger('warning')
info = logging.getLogger('info')


if __name__ == "__main__":
    info.info('hello world')
    error.info('hello world')

after run this script, file info.log has one 'hello world' and error.log also has only one 'hello world'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM