使用dictconfig进行Python Loggly日志记录设置

时间:2015-07-27 16:21:12

标签: python logging https loggly

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

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

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

1 个答案:

答案 0 :(得分:3)

此方法使用标准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'文件,您可以使用以下字典(替换您的密钥):

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

您也可以直接在控制台上测试(不要忘记添加密钥):

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")