elasticsearch,logging,filebeat,Python,elasticsearch,Logging,Filebeat" /> elasticsearch,logging,filebeat,Python,elasticsearch,Logging,Filebeat" />

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

Python-使用structlog从多个模块进行日志记录,python,elasticsearch,logging,filebeat,Python,elasticsearch,Logging,Filebeat,我正在尝试使用Structlog登录到一个文件,然后使用filebeat将日志发送到我的日志服务 我已经让一切都正常工作了,但我希望能够跨多个模块使用相同的记录器,就像Pythons默认记录器一样(请参阅“从多个模块记录”) 原因之一是我想将sessionID绑定到我的logoutput,该logoutput应该记录在此会话中调用的所有模块 可能需要一些关于如何使用structlogger的基本知识,但在他们的文档或其他帖子中没有找到答案 请告知 例如: main.py #!/usr/bin/e

我正在尝试使用Structlog登录到一个文件,然后使用filebeat将日志发送到我的日志服务

我已经让一切都正常工作了,但我希望能够跨多个模块使用相同的记录器,就像Pythons默认记录器一样(请参阅“从多个模块记录”)

原因之一是我想将sessionID绑定到我的logoutput,该logoutput应该记录在此会话中调用的所有模块

可能需要一些关于如何使用structlogger的基本知识,但在他们的文档或其他帖子中没有找到答案

请告知

例如:

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

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

您需要使用包装字典作为上下文类,如

所以你会得到这样的结果:

structlog.configure(
处理器=[
structlog.stdlib.filter_by_level,
#其他处理器
],
context_class=structlog.threadlocal.wrap_dict(dict),
)