相关疑难解决方法(0)

使用Python日志记录模块时,日志输出重复

我正在使用python logger.以下是我的代码:

import os
import time
import datetime
import logging
class Logger :
   def myLogger(self):
      logger = logging.getLogger('ProvisioningPython')
      logger.setLevel(logging.DEBUG)
      now = datetime.datetime.now()
      handler=logging.FileHandler('/root/credentials/Logs/ProvisioningPython'+ now.strftime("%Y-%m-%d") +'.log')
      formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
      handler.setFormatter(formatter)
      logger.addHandler(handler)
      return logger
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是我在每个logger.info调用的日志文件中都有多个条目.我怎么解决这个问题?

python

89
推荐指数
10
解决办法
5万
查看次数

打印到屏幕并同时写入文件

我在网上发现了一些通常有效的代码,但我想在同一个程序中多次使用它(将不同的东西写入不同的文件,同时仍然一直打印到屏幕上).

也就是说,当它关闭时,我认为sys.stdout关闭,所以打印完全,并再次使用这个类失败.我尝试重新导入sys和其他愚蠢的东西,但我无法让它工作.

这是该网站,代码为groups.google.com/group/comp.lang.python/browse_thread/thread/d25a9f5608e473af/

import sys

class MyWriter:

    def __init__(self, stdout, filename):
        self.stdout = stdout
        self.logfile = file(filename, 'a')

    def write(self, text):
        self.stdout.write(text)
        self.logfile.write(text)

    def close(self):
        self.stdout.close()
        self.logfile.close()

writer = MyWriter(sys.stdout, 'log.txt')
sys.stdout = writer

print 'test' 
Run Code Online (Sandbox Code Playgroud)

python

41
推荐指数
3
解决办法
4万
查看次数

你如何运行OpenERP yaml单元测试

我正在尝试在我的openERP模块上运行单元测试,但无论我写什么,它都不会显示测试是否通过!有谁知道如何输出测试结果?(使用Windows OpenERP 6.1版)

我的YAML测试是:

- 
  I test the tests
-
  !python {model: mymodelname}: |
    assert False, "Testing False!"
    assert True, "Testing True!"
Run Code Online (Sandbox Code Playgroud)

我用openerp-server.exe重新加载模块时的输出--update mymodule --log-level = test -dtestdb显示测试运行但没有错误?!

... TEST testdb openerp.tools.yaml_import: I test the tests
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

编辑:------------------------------------------------ ---------------------

好吧,经过多次摆弄!python,我尝试了另一个测试:

- 
    I test that the state
-
!assert {model: mymodel, id: mymodel_id}:
    - state == 'badstate'
Run Code Online (Sandbox Code Playgroud)

这给了预期的失败:

WARNING demo_61 openerp.tools.yaml_import: Assertion "NONAME" FAILED
test: state == 'badstate'
values: ! active == badstate
Run Code Online (Sandbox Code Playgroud)

所以我猜我的语法有问题,可能会在版本7中按预期工作.

感谢大家的回答和帮助!

yaml unit-testing openerp openerp-8

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

Python3添加日志记录级别

我有这个代码对我来说很好.

import logging
import logging.handlers

logger = None


def create_logger():
    global logger
    logger = logging.getLogger('Logger')
    logger.setLevel(logging.DEBUG)
    handler = logging.handlers.RotatingFileHandler("C:/Users/user/Desktop/info.log", maxBytes=1000000, backupCount=20)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)


create_logger()
logger.info("Text info")
logger.debug("Text debug")
logger.warning("Text warning")
logger.error("Text error")
logger.critical("Text critical")
Run Code Online (Sandbox Code Playgroud)

输出看起来很棒:

2017-12-19 15:06:43,021 - 记录器 - 信息 - 文本信息
2017-12-19 15:06:43,021 - 记录器 - 调试 - 文本调试
2017-12-19 15:06:43,022 - 记录器 - 警告 - 正文警告
2017-12-19 15:06:43,022 - 记录器 - 错误 - 文本错误
2017-12-19 15:06:43,022 - 记录器 …

python logging python-3.5

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

Python记录器不尊重setLevel?

我花了一些时间在Python记录器上查看网站问题,希望我能在那里得到解决.我已经设置了一个带有两个流处理程序的记录器,它们具有不同的格式和级别的日志记录,这是我的代码库中的功能代码段:

import os
import time
import logging

LOG_LEVELS = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
TEST_RESULT_LEVELV_NUM = 51

# http://stackoverflow.com/a/11784984/196832
def status(self, message, *args, **kws):
    self._log(TEST_RESULT_LEVELV_NUM, message, args, **kws)

logging.addLevelName(TEST_RESULT_LEVELV_NUM, "RESULT")
logging.Logger.result = status


def setup_logging(level=0, quiet=False, logdir=None):
    logger = logging.getLogger('juju-test')
    ffmt = logging.Formatter('%(asctime)s %(name)s %(levelname)-8s: %(message)s')
    cfmt = logging.Formatter('%(name)s %(levelname)s: %(message)s')
    #logger.setLevel(0)

    if level >= len(LOG_LEVELS):
        level = len(LOG_LEVELS) - 1

    if logdir:
        if not os.path.exists(logdir):
            os.makedirs(logdir)
        logfile = os.path.join(logdir, 'juju-test.%s.log' % int(time.time()))
        fh = logging.FileHandler(logfile)
        # Always at least log …
Run Code Online (Sandbox Code Playgroud)

python logging

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

Ignore specific logging line temporarily

I have a method called import_customers() which loads csv-like data.

This methods logs to log-level INFO.

In one case I want to avoid this logging.

I see several ways:

Variant 1: a new kwarg like do_logging=True which I can switch to false.

Variant 2: Use some magic context which ignores this line.

with IgnoreLoggingContext() as context:
    import_customers()
Run Code Online (Sandbox Code Playgroud)

How could I implement IgnoreLoggingContext()?

If you think V1 is better, then please leave a comment.

python logging

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

使用 Python 3.7 添加日志级别

我一直在尝试通过以下两个优秀的帖子来添加自定义日志级别:

如何向 Python 的日志记录工具添加自定义日志级别

Python3添加日志级别

在我的顶层 __init__.py 中,我放置了:

    import logging

    logging.VERBOSE = 15 
    logging.addLevelName(logging.VERBOSE, "VERBOSE")

    def verbose(self, message, *args, **kws):
        if self.isEnabledFor(logging.VERBOSE):
            # Yes, logger takes its '*args' as 'args'.
            self._log(logging.VERBOSE, message, args, **kws) 

    setattr(logging, 'verbose', verbose)
    setattr(logging.Logger, 'verbose',verbose)
#also tried
# logging.Logger.verbose=verbose
# logging.verbose=verbose

logging.getLogger(__name__).addHandler(logging.NullHandler())
Run Code Online (Sandbox Code Playgroud)

在其他各种类和子模块中,我希望我可以:

import logging
.
.
.
logging.verbose("Someone sent us up the bomb")
Run Code Online (Sandbox Code Playgroud)

但是,让我感动的是:

TypeError: verbose() missing 1 required positional argument: 'message'
Run Code Online (Sandbox Code Playgroud)

如果我切换到:

logging.log(logging.VERBOSE, "Intent Returned: " + intent_name)
Run Code Online (Sandbox Code Playgroud)

我没有抛出异常,但也没有打印任何消息。

logging python-3.7

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