我正在以这种方式使用 Python 日志记录:
logger = logging.getLogger("my_logger")
logger.info("Some text.")
Run Code Online (Sandbox Code Playgroud)
我有一堆物联网设备都在运行(制作日志)。他们将日志数据流式传输到数据库。为了区分来源,我需要包括来源 IP 地址。
有没有办法使用日志记录获取主机名?是否在 LogRecords 中跟踪/跟踪 IP 地址或主机名?
一般来说,将主机名添加到 LogRecord 的最佳方法是什么?
问题
如何在 PyCharm 中传递多个 pytest 命令行选项?
问题
设置 pytest 日志记录选项--log-level=DEBUG --log-cli=True --log-cli-level=DEBUG失败,并出现 PyCharm 运行配置错误。
Launching pytest with arguments --log-level=DEBUG --log-cli=True --log-cli-level=DEBUG ****/test_040_objective_sigmoid.py in ****
ERROR: usage: _jb_pytest_runner.py [options] [file_or_dir] [file_or_dir] [...]
_jb_pytest_runner.py: error: unrecognized arguments: --log-cli=True
inifile: None
rootdir: ****
Run Code Online (Sandbox Code Playgroud)
使用单个参数,它运行时不会出现错误。
Launching pytest with arguments --log-level=DEBUG ****test_040_objective_sigmoid.py in ****
============================= test session starts ==============================
platform linux -- Python 3.8.5, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 -- ****/bin/python
cachedir: .pytest_cache
rootdir: ****
plugins: pytest_check-1.0.1
collecting ... collected 5 items
Run Code Online (Sandbox Code Playgroud)
从命令行运行 pytest 时,pytest …
我有很多用 python django 编写的应用程序代码,每个应用程序都使用标准的 python 记录器模块,并且只记录了一个简单的消息字符串。
现在有什么方法可以添加我自己的客户中间件或 django 应用程序,当在他们的方法中调用日志记录时,它应该到达我的函数,我将为日志添加更多值,制作正确的 json 格式,然后写入日志文件。这样在当前的应用程序开发人员不需要做很多改变,除了他需要添加我的 django 应用程序或中间件
是否可以有多个日志处理程序在 python 日志记录配置中引用同一个日志文件。handler_two我可以通过向对象添加一个处理程序来使其工作handlers,但这似乎是一个样板文件。
"handler_two": {
"level": "DEBUG",
"class": "logging.handlers.TimedRotatingFileHandler",
"formatter": "verbose",
"filename": "{}/abc.log".format(log_folder),
"when": "midnight",
"backupCount": 10,
"encoding": "utf8"
},
Run Code Online (Sandbox Code Playgroud)
日志记录.conf -
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"format": "%(asctime)s %(name)s %(levelname)s (PID: %(process)d) %(message)s",
"datefmt": "%d/%m/%Y %I:%M:%S %p %Z"
},
"simple": {
"format": "%(asctime)s %(name)s %(levelname)s > %(message)s"
}
},
"handlers": {
"handler_one": {
"level": "DEBUG",
"class": "logging.handlers.TimedRotatingFileHandler",
"formatter": "verbose",
"filename": "{}/abc.log".format(log_folder),
"when": "midnight",
"backupCount": 10,
"encoding": "utf8"
},
"error": {
"level": "ERROR", …Run Code Online (Sandbox Code Playgroud) 本节的前三段指出可以使用 {} 格式来记录格式字符串。
如果您使用 {} 格式 (str.format()),则可以使用 {attrname} 作为格式字符串中的占位符。
然而,它不起作用。
import logging
logging.basicConfig(level=logging.INFO, format='[{asctime}] {message}')
logging.info('foo')
Run Code Online (Sandbox Code Playgroud)
印刷,
[{asctime}] {message}
Run Code Online (Sandbox Code Playgroud)
怎么了?
我想添加我的程序达到日志输出的秒数。
relativeCreated 我在这里找到了,但它会给我毫秒,例如:
logging.basicConfig(format='{relativeCreated:8.0f}ms {levelname:s} {message:s}', style="{")
Run Code Online (Sandbox Code Playgroud)
结果是
4081ms INFO my message
6012ms INFO another message
Run Code Online (Sandbox Code Playgroud)
但由于我预计运行时间以小时为单位,所以我更愿意。
4s INFO my message
6s INFO another message
Run Code Online (Sandbox Code Playgroud)
我试过
logging.basicConfig(format='{relativeCreated / 1000:4.0f}s {levelname:s} {message:s}', style="{")
Run Code Online (Sandbox Code Playgroud)
但这会导致
KeyError: 'relativeCreated / 1000'
Run Code Online (Sandbox Code Playgroud) 当我尝试使用每个模块的命名记录器写入日志时,如果没有专门为命名记录器配置的处理程序,我希望日志将传播到根记录器。当我使用时,这工作得很好basicConfig,但是当我使用时dictConfig,来自指定记录器的日志消息会被丢弃。
如何让指定的记录器正确写出日志消息?
foo.py:
import logging
logger = logging.getLogger('foo')
def doFoo(text):
logger.debug(text)
logger.info(text)
logger.warn(text)
logger.error(text)
Run Code Online (Sandbox Code Playgroud)
主要.py:
import json
import logging.config
import foo
# logging.basicConfig(level=logging.DEBUG) # works as expected with this
with open('logging-config.json') as f:
config = json.load(f)
logging.config.dictConfig(config['logging'])
logging.info('starting')
foo.doFoo('this is a test')
Run Code Online (Sandbox Code Playgroud)
日志记录-config.json:
{
"logging": {
"version": 1,
"formatters": {
"standard": {
"class": "logging.Formatter",
"datefmt": "%Y-%m-%d %H:%M:%S",
"format": "%(asctime)s %(name)s %(levelname)s: %(message)s"
}
},
"handlers": {
"stdout": {
"class": "logging.StreamHandler", …Run Code Online (Sandbox Code Playgroud) 这似乎是一个非常简单的问题,但我找不到任何很好的例子。
我想过滤一个具有特定名称的记录器。
例如
import logging
logging.root.setLevel(logging.DEBUG)
logging.root.addHandler(logging.StreamHandler())
logging.root.addFilter(logging.Filter(name="a"))
a = logging.getLogger("a")
b = logging.getLogger("b")
a.info("aaaaa")
b.info("bbbbb")
Run Code Online (Sandbox Code Playgroud)
我希望 root 记录器会过滤消息,b因为我知道logging.Filter只通过nameor childs of the name.
但正如您所料,它只会传递所有消息。
我有什么误解?
我使用 Django 进行日志记录配置如下:
LOGGING = {
'version':1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{asctime} {process:d} {thread:d} {levelname} {name} {module} {funcName} {message}',
'style': '{',
}
},
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': BASE_DIR+'/logs/django_logs.log',
'backupCount': 14,
'maxBytes': 52428800,
'formatter': 'verbose'
}
},
'loggers': {
'': {
'handlers': ['file'],
'level': 'INFO'
}
},
}
Run Code Online (Sandbox Code Playgroud)
我正在运行 16 个 django 进程,几个用于 websocket 的 daphne 和几个用于基于 django Rest 框架的正常 API 调用的 Gunicorn 进程。但是当我查看日志时,会同时记录多个文件。例如,django_logs.1 .... django.logs.14 同时登录。我是否必须添加其他内容来一次记录到一个文件,并仅在其大小超过日志文件的指定大小时才轮换它?
有关额外信息,我使用 python 3.6.8 并在每个项目文件中初始化记录器,如下所示:
import logging …Run Code Online (Sandbox Code Playgroud) python django python-3.x django-rest-framework python-logging
我在 Windows 10 上使用 VS Code 1.73.1,并使用 Pythonlogging模块改造我的程序。我的程序总体运行正常。我做的主要事情是将所有打印语句更改为,logger.debug并且我知道变量格式需要从更改{}为%s。我还将该encoding标志添加到我的文件处理程序中。
还有几件事:
F5函数运行它时,它不会创建文件或在任何地方显示任何控制台输出。print('something')根据设置在终端或调试控制台中工作并显示launch.json,但logger.debug('something')不在任一控制台中显示。
我的请求/问题: 使用logger.debug,为什么没有任何内容打印到控制台,甚至没有创建文件?
我还尝试在其自己的单独文件中运行下面的代码.py,但出现同样的问题:
print显示到调试控制台,但logger.debug没有。
记录代码块:
import logging
# Create a custom logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Streaming Handler
c_handler = logging.StreamHandler()
c_handler.setLevel(logging.INFO)
c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
c_handler.setFormatter(c_format)
logger.addHandler(c_handler)
# File Handler
f_handler = logging.FileHandler('download_shelf.log', encoding='utf-8')
f_handler.setLevel(logging.DEBUG)
f_format …Run Code Online (Sandbox Code Playgroud) python-logging ×10
python ×8
logging ×5
django ×2
python-3.x ×2
filter ×1
pycharm ×1
pytest ×1
python-2.7 ×1