小编Dea*_*tar的帖子

Python 日志记录重复日志消息

我正在尝试使用我自己的函数将消息记录到 sys.stdout 和文件中以设置相同的格式。当我登录到文件或函数之外时,一切都会按预期进行。当我将消息发送到我的函数时,我收到重复的消息:

def log(lvl, msg):
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        filename='/tmp/test.log',
                        filemode='a')

    console = logging.StreamHandler(sys.stdout)
    console.setLevel(logging.INFO)
    formatter = logging.Formatter('%(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)
    logging.log(lvl, "%s: %s" % (options.build_node, msg))

if __name__ == "__main__":

    print "Executing outside of the function"
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        filename='/tmp/test.log',
                        filemode='a')
    console = logging.StreamHandler(sys.stdout)
    console.setLevel(logging.INFO)
    formatter = logging.Formatter('%(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)
    logging.log(logging.INFO, "some message")
    logging.log(logging.ERROR, "some error message")
    logging.log(logging.WARN, "Warning message")
    logging.log(logging.INFO, "another info message")     

    print "\nNow calling the log function"
    log(logging.INFO, "some …
Run Code Online (Sandbox Code Playgroud)

python logging duplicates

1
推荐指数
1
解决办法
2190
查看次数

标签 统计

duplicates ×1

logging ×1

python ×1