使用 dictconfig 的 Python Loggly 日志记录设置

标签 python logging https loggly

我想在我的新 PaaS python 应用程序中尝试 Loggly,因为我通常针对 Linux 服务器进行编码,并且只使用标准旋转文件处理程序。这提出了一个问题,因为他们记录的配置仅涵盖使用 .conf 文件,并且由于他们在首选 HTTPS 处理程序中有一些自定义方法,因此有一些技巧可以以其他方式配置它。

我一直在使用嵌套的 .py 文件来处理应用程序其余部分的配置,并且不想更改,而且文档中似乎首选 dictconfig 方法。

那么,如何解决这个问题呢?

最佳答案

该方法使用了标准python日志模块的dictconfig方法,并在2.7.9上进行了测试

安装“loggly-python-handler”模块。

在您的代码中,您可以执行以下操作,其中“conf”是您的 .py 配置文件:

import logging, logging.config
import loggly.handlers
import conf

# Init Logging
logging.config.dictConfig(conf.LOGGING)
logger = logging.getLogger(u'root')

然后,在“conf.py”文件中,您可以使用以下字典(替换您的 key ):

LOGGING = {
    u'version': 1,
    u'handlers': {
        u'loggly': {
            u'class': u'loggly.handlers.HTTPSHandler',
            u'formatter': u'basic',
            u'level': u'DEBUG',
            u'url': u'https://logs-01.loggly.com/inputs/YOUR_KEY_HERE/tag/pytest'
        },
        u'console': {
            u'class': u'logging.StreamHandler',
            u'level': u'DEBUG',
            u'formatter': u'basic',
            u'stream': u'ext://sys.stdout',
        }
    },
    u'formatters': {
        u'basic': {
            u'format': u'%(asctime)s | %(name)15s:%(lineno)3s:%(funcName)15s | %(levelname)7s | %(message)s'
        }
    },
    u'loggers': {
        u'root': {
            u'level': u'DEBUG',
            u'handlers': [u'console', u'loggly']
        }
    }
}

这是日志模块文档中使用 dictconfig 的说明的组合:https://docs.python.org/2/library/logging.config.html

并深入研究“loggly-python-handler”模块的代码,看看它的构造函数是如何工作的:https://github.com/psquickitjayant/loggly-python-handler/blob/master/loggly/handlers.py

您还可以直接从控制台进行测试(不要忘记添加您的 key ):

import logging
import loggly.handlers
handler = loggly.handlers.HTTPSHandler(url='https://logs-01.loggly.com/inputs/YOUR_KEY_HERE/tag/python')
logger = logging.getLogger(u'root')
logger.addHandler(handler)
logger.warning("test loggly connection")

关于使用 dictconfig 的 Python Loggly 日志记录设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31658292/

相关文章:

python - Paraview:从积分变量中获取点数据

ssl - 自定义 (https) header 是一种安全的 API 身份验证方法吗?

security - 通过 HTTP 发送 Web 表单例份验证数据的最佳方式是什么?

java - Spring库中的REST(RestTemplate)是否支持HTTPS协议(protocol)?

python - 在尝试组合两个数组时,我在 numpy 中遇到类型问题

python - 查找重复邮寄地址的策略

python - 删除和/或更新系统的 Python 时虚拟环境的后果

logging - NLog 自定义 LayoutRenderer 不工作

Python 记录器不适用于带有 apache 的 django

android - 如何使用 Kotlin 协程写入文件。是否可以创建 FIFO?