即使在设置日志级别后,我的日志也会在日志文件中打印两次。需要在这里修复什么

时间:2018-01-10 06:26:04

标签: python logging

logger.py
=========
import logging

level = logging.INFO
filename = "xyz.txt"
class printlog():
    #def __init__(self):

    @staticmethod
    def debug(msg):
        print("In Debug")
        logger = logging.getLogger(__name__)
        logger.setLevel(level)
        handler = logging.FileHandler(filename)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.debug(msg)

    @staticmethod
    def info(msg):
        print("In Debug")
        logger = logging.getLogger(__name__)
        logger.setLevel(level)
        handler = logging.FileHandler(filename)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.info(msg)

    @staticmethod
    def warning(msg):
        print("In Warning")
        logger = logging.getLogger(__name__)
        logger.setLevel(level)
        handler = logging.FileHandler(filename)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.warning(msg)
    @staticmethod
    def error(msg):
        print("In Error")
        logger = logging.getLogger(__name__)
        logger.setLevel(level)
        handler = logging.FileHandler(filename)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.error(msg)       


_____________________________
====
main.py
=======
from test1 import printlog


plog = printlog()
plog.debug('Hello debug')
plog.info('hello info')
plog.error('hello error')
plog.warning('hello warning')
--------------------

When I run main.py I get the below output. The solution required for me is that it should print messages only once(1). Whereas in the below output, it prints multiple times. Please help.
  

2018-01-10 11:42:48,961 - test1 - INFO - 你好信息
  2018-01-10 11:42:48,961 - test1 - INFO - 你好信息
  2018-01-10 11:42:48,961 - test1 - ERROR - 你好错误
  2018-01-10 11:42:48,961 - test1 - ERROR - 你好错误
  2018-01-10 11:42:48,961 - test1 - ERROR - 你好错误
  2018-01-10 11:42:48,961 - test1 - 警告 - 你好警告
  2018-01-10 11:42:48,961 - test1 - 警告 - 你好警告
  2018-01-10 11:42:48,961 - test1 - 警告 - 你好警告
  2018-01-10 11:42:48,961 - test1 - 警告 - 你好警告

0 个答案:

没有答案