简体   繁体   English

自定义 Python 日志记录方法

[英]Custom Python logging method

I'd like to use python-logstash in my Django application and need to pass 'extra' fields.我想在我的 Django 应用程序中使用python-logstash并且需要传递“额外”字段。 Here are the docs .这是文档

extra = {"app":"app-live","source":"django_log"}

I would prefer not to go through and change all of my logger calls, for example:我不想经历并更改我所有的记录器调用,例如:

logger.info('Information blah.') to logger.info('Information blah.', extra=extra) logger.info('Information blah.') to logger.info('Information blah.', extra=extra)

The extra will be the same for every single call and is required.每次通话的extra都是相同的,并且是必需的。 I would prefer to override the existing logger methods so that I can just do this once.我更愿意覆盖现有的记录器方法,这样我就可以只做一次。

Is there a way to do this in the logging handlers in the Django settings.py or how and where can I override the logger methods to always add the extra args?有没有办法在 Django settings.py的日志处理程序中执行此操作,或者如何以及在哪里覆盖记录器方法以始终添加extra参数?

You should be able to do that globally with a Filter as described in the logging cookbook .您应该能够使用 过滤器在全局范围内执行此操作,如日志记录手册中所述

To simplify things a bit, Django provides a CallbackFilter .为了稍微简化一下,Django 提供了一个CallbackFilter Your filter function would look like this:您的过滤器功能如下所示:

def logstash_filter(record):
    record.app = 'app-live'
    record.source = 'django_log'
    return True

And your logging config something like this.你的日志配置是这样的。

...
'filters': {
    'add_logstash_info': {
        '()': 'django.utils.log.CallbackFilter',
        'callback': logstash_filter,
    }
},
'handlers': {
    'logstash': {
        ...
        'filters': ['add_logstash_info'],
    },
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM