我最近将我的脚本从 2.x 移植到 3.x。在通过自动化 (rundeck) 运行的生产过程中,我们看到由于记录器未处理阻塞 I/O 而导致的错误。任何如何解决的想法都会很棒。
--- Logging error ---
Traceback (most recent call last):
File "/usr/lib/python3.6/logging/__init__.py", line 998, in emit
self.flush()
File "/usr/lib/python3.6/logging/__init__.py", line 978, in flush
self.stream.flush()
BlockingIOError: [Errno 11] write could not complete without blocking
Run Code Online (Sandbox Code Playgroud) I have the following handler configuration for logging:
"handlers": {
'system_file': {
'level': 'DEBUG',
'class': 'logging.handlers.TimedRotatingFileHandler',
'filename': os.path.join(LOG_FOLDER, "all.log"),
'formatter': 'verbose',
'when': 'midnight',
'backupCount': '30',
}
}
Run Code Online (Sandbox Code Playgroud)
Now based on this configuration my logs should get rotated every midnight, i.e it should create date wise logs.
In the all.log file, everything gets logged properly with correct timestamp, but when the rotation happens, I do not see all the logs in the backup log files (previous day log files).
For example: …
Python 3.8.0,pytest 5.3.2,日志记录 0.5.1.2。
我的代码有一个输入循环,为了防止程序完全崩溃,我捕获任何抛出的异常,将它们记录为关键,重置程序状态,然后继续运行。这意味着导致这种异常的测试不会完全失败,只要输出仍然是预期的。如果错误是测试代码的副作用但不影响主要测试逻辑,则可能会发生这种情况。但是,我仍然想知道该测试暴露了一个导致错误的错误。
我所做的大部分谷歌搜索都显示了如何在 pytest 中显示日志的结果,我正在这样做,但我不知道是否有办法在测试中公开日志,这样我就可以在任何测试中失败错误或严重级别的日志。
编辑:这是失败尝试的最小示例:
test.py:
import subject
import logging
import pytest
@pytest.fixture(autouse=True)
def no_log_errors(caplog):
yield # Run in teardown
print(caplog.records)
# caplog.set_level(logging.INFO)
errors = [record for record in caplog.records if record.levelno >= logging.ERROR]
assert not errors
def test_main():
subject.main()
# assert False
Run Code Online (Sandbox Code Playgroud)
subject.py:
import logging
logger = logging.Logger('s')
def main():
logger.critical("log critical")
Run Code Online (Sandbox Code Playgroud)
运行python3 -m pytest test.py通过没有错误。取消对 assert 语句的注释使测试失败且没有错误,并打印[]到 stdout 和log criticalstderr。
编辑2:
我找到了为什么会失败。从关于 caplog 的文档: …
我是 Flask 新手,在过滤某些日志时遇到问题。我的用例很简单:我不想记录运行状况检查查询,该查询命中了路线/health。
这是我所拥有的:
from flask import Flask
from flask.logging import logging
class NoHealth(logging.Filter):
def filter(self, record):
return 'GET /health' not in record.getMessage()
no_health = NoHealth()
app = Flask(__name__)
app.logger.addFilter(no_health)
app.logger.setLevel('INFO')
@app.route('/health')
def health_check():
return "OK"
Run Code Online (Sandbox Code Playgroud)
我想要删除的日志如下所示:
127.0.0.1 - - [31/Mar/2020 17:51:03] "GET /health HTTP/1.1" 200 -
然而,他们仍然在渡过难关。我缺少什么?
请帮助我,如何将python脚本日志发送到syslog服务器(syslog-ng产品),我已经尝试过以下方法..它有两种方法。一个是“SysLogHandler”,另一个是“SocketHandler”
import logging
import logging.handlers
import socket
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address=('10.10.11.11', 611), socktype=socket.SOCK_STREAM)
#handler = logging.handlers.SocketHandler('10.10.11.11', 611)
my_logger.addHandler(handler)
my_logger.debug('this is debug')
my_logger.critical('this is critical')
Run Code Online (Sandbox Code Playgroud)
结果:SysLogHandler
[ansible@localhost ~]$ python test.py
Traceback (most recent call last):
File "test.py", line 8, in <module>
handler = logging.handlers.SysLogHandler(address=('10.10.11.11', 611), socktype=socket.SOCK_STREAM)
File "/usr/lib64/python3.6/logging/handlers.py", line 847, in __init__
raise err
File "/usr/lib64/python3.6/logging/handlers.py", line 840, in __init__
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused #THIS IS OK for me since server unreachable.
Error in atexit._run_exitfuncs:
Traceback …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用TimedRotatingFileHandler实现 python 日志记录
我在日志文件名中添加文件扩展名时遇到问题
这是我的代码
Path(".\\Log").mkdir(parents=True, exist_ok=True)
LOGGING_MSG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
LOGGING_DATE_FORMAT = '%m-%d %H:%M:%S'
formatter = logging.Formatter(LOGGING_MSG_FORMAT, LOGGING_DATE_FORMAT)
handler = TimedRotatingFileHandler(".\\Log\\info.log",'midnight',1)
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
root_logger = logging.getLogger()
root_logger.addHandler(handler)
Run Code Online (Sandbox Code Playgroud)
第一次使用此代码时,我按预期获得文件名“info.log”,但是当它滚动到午夜时,我得到的文件名是“info.log.2020-05-22”,但我是什么期待的是“info.2020-05-22.log”。
我如何将处理程序后缀附加到文件扩展名(.log)之前?
我正在尝试配置 Python 日志记录框架来处理来自multiprocessing.Pool. 在大多数情况下,脚本将无限期挂起,尽管已经观察到一些其他行为,例如退出而不打印所有日志消息。
我的实际代码更复杂,但我已将其简化为以下脚本,该脚本在我测试过的计算机上相当可靠地中断。
#!/usr/bin/env python3
import logging
import logging.handlers
import multiprocessing
import multiprocessing.util
L = logging.getLogger(__name__)
_globalQueue = None
_globalListener = None
def basicsetup():
global _globalQueue
global _globalListener
cf = logging.Formatter("[{levelname}] {created:.7f} {name} ({process}~{processName}): {message}", style="{")
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(cf)
# Subprocesses should use the queue to send log messages back to a thread in the main process
_globalQueue = multiprocessing.Queue()
_globalListener = logging.handlers.QueueListener(_globalQueue, handler, respect_handler_level=True)
_globalListener.start()
# Configure logging for main thread
process_setup(get_queue())
def …Run Code Online (Sandbox Code Playgroud) python multiprocessing python-multiprocessing python-logging
我希望我的代码使用 pythonlogging来记录异常。在我通常使用的代码中await,通常会引发异常,因此:
try:
await code_that_can_raise()
except Exception as e:
logger.exception("Exception happended")
工作正常。
然而,当使用
loop.create_task(coro())
我不确定如何在此处捕获异常。
包装 create_task() 调用显然不起作用。在代码中记录每个异常的最佳解决方案是什么?
我在uvicorn的源代码中看到了一个 python dict 日志配置。
在那,他们将格式化程序定义为
{
"default": {
"()": "uvicorn.logging.DefaultFormatter",
"fmt": "%(levelprefix)s %(asctime)s %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
},
"access": {
"()": "uvicorn.logging.AccessFormatter",
"fmt": '%(levelprefix)s %(asctime)s :: %(client_addr)s - "%(request_line)s" %(status_code)s',
"use_colors": True
},
}Run Code Online (Sandbox Code Playgroud)
此外,我们可以看到,他们定义了一个空的记录器(不知道我应该怎么称呼它),
"": {"handlers": ["default"], "level": "INFO"},
^^^^ - see, Empty key
Run Code Online (Sandbox Code Playgroud)
所以,这是我的问题,
"()"在做格式化蟒蛇记录的部分?""在做伐木工人部分蟒蛇记录?我正在尝试在 AWS lambda 中运行脚本,并且希望在脚本运行后将信息级别日志输出到控制台。我尝试从这篇关于在 lambda 购买中使用日志的文章中寻求帮助,但没有取得任何成功。我认为 AWS Cloudwatch 正在覆盖我的配置,如下所示。
import logging
# log configuration
logging.basicConfig(
format='%(levelname)s: %(message)s',
level=logging.INFO,
encoding="utf-8"
)
Run Code Online (Sandbox Code Playgroud)
我想将日志记录级别设置为logging.info。我怎样才能做到这一点?运行时是python 3.9
python-logging ×10
python ×9
logging ×3
python-3.x ×2
aws-lambda ×1
django ×1
exception ×1
flask ×1
pytest ×1
syslog ×1
uvicorn ×1