简体   繁体   English

Python - 使用 structlog 从多个模块记录日志

[英]Python - Logging from multiple modules using structlog

I am trying to use Structlog to to log to a file and then using filebeat to send the log to my logging service.我正在尝试使用 Structlog 登录到文件,然后使用 filebeat 将日志发送到我的日志记录服务。

I have made the everything work, but I would like to be able to use the same logger across multiple modules, like with Pythons default logger (see https://docs.python.org/2/howto/logging.html section "Logging from multiple modules").我已经使一切正常,但我希望能够在多个模块中使用相同的记录器,就像 Python 的默认记录器一样(参见https://docs.python.org/2/howto/logging.html部分“Logging来自多个模块”)。

One of the reasons is that I would like to bind a sessionID to my logoutput that should be logged across all modules called from this session.原因之一是我想将 sessionID 绑定到我的日志输出,该日志输出应该在从此会话调用的所有模块中记录。

Probably need some fundamental knowledge on how to use structlogger, but havn't found the answer in their documentation or in other posts.可能需要一些关于如何使用 structlogger 的基本知识,但还没有在他们的文档或其他帖子中找到答案。

Please advice....请指教....

An example:一个例子:

main.py主文件

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import uuid

from mylogger import myLogger
import otherModule

myLogger = myLogger()

myLogger.log.warning('working', error='test')

myLogger.log = myLogger.log.bind(sessionID=str(uuid.uuid4()))

myLogger.log.warning('Event where sessionID is bound to logger', error='test')

otherModule = otherModule.otherModule()

myLogger.py我的记录器

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import datetime, logging
from structlog import wrap_logger, get_logger
from structlog.processors import JSONRenderer
from structlog.stdlib import filter_by_level, add_log_level


class myLogger():
    def __init__(self, loggername="root", logLevel='INFO', logFile='test2.log'):

        self.log = wrap_logger(
            logging.getLogger('root'),
            processors=[
                filter_by_level,
                add_log_level,
                self.add_timestamp,
                JSONRenderer(indent=1, sort_keys=True)
            ]
        )

        logging.basicConfig(format='%(message)s', level=logLevel, filename=logFile)

    def my_get_logger(self, loggername="AnyLogger"):
        log = get_logger(loggername)

        return log

    def add_timestamp(self,  _, __, event_dict):
        event_dict['timestamp'] = datetime.datetime.utcnow().isoformat()
        return event_dict

otherModule.py其他模块.py

import structlog
from mylogger import myLogger

class otherModule():
    def __init__(self):
        logger = structlog.get_logger('root')
        ## This logger does not have the processors nor the bound sessionID

        logger.warning('In other module')
        ## This logmessage is printed to console

        logger2 = myLogger();
        ## This logger has all the processors  but not the bund sessionID

        logger2.log.warning('In other module')
        ## This log is written to my logfile, but without the sessionID

You need to use a wrapped dictionary as a context class as explained in the structlog documentation您需要使用包装字典作为上下文类,如structlog 文档中所述

So you will end up with something like this:所以你最终会得到这样的结果:

structlog.configure(
    processors=[
        structlog.stdlib.filter_by_level,
        # other processors
    ],
    context_class=structlog.threadlocal.wrap_dict(dict),
)

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

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