簡體   English   中英

Python 日志記錄:使用日志記錄模塊將數據記錄到服務器

[英]Python logging : Log data to server using the logging module

日志模塊提供了使用 HTTPHandler 的可能性,由於格式的限制,它不符合我的要求。

如文檔中所述, https://docs.python.org/3/library/logging.handlers.html 對 HTTP使用 setFormatter() 沒有指定 aHandler 的效果。

我的目標是在我的應用程序中記錄事件,並在本地服務器上收集它們。 我正在使用 JSON-Server 來模擬 REST API ( https://github.com/typicode/json-server )。 我已經參考了這個鏈接: 如何為 python 日志設置 HTTPHandler ,作為一種可能的解決方案,但我無法獲得所需的內容。

我的代碼:

"""class CustomHandler(logging.handlers.HTTPHandler):
    def __init__(self):
        logging.handlers.HTTPHandler.__init__(self)

    def emit(self, record):
        log_entry = self.format(record)
        # some code....
        url = 'http://localhost:3000/posts'
        # some code....
        return requests.post(url, log_entry, json={"Content-type": "application/json"}).content """

def custom_logger(name):

    logger = logging.getLogger(name)

    formatter_json = jsonlogger.JsonFormatter(
        fmt='%(asctime)s %(levelname)s %(name)s %(message)s') 

    requests.post('http://localhost:3000/posts', json= {"message" : "1" } ) 

 
    filehandler_all = logging.FileHandler('test.log')
    filehandler_all.setLevel(logging.DEBUG)
    filehandler_all.setFormatter(formatter_json)           
    logger.addHandler(filehandler_all)


    #http_handler = logging.handlers.HTTPHandler('http://localhost:3000' ,
     #"/posts", "POST")
    #
    # http_handler = CustomHandler()
   # http_handler.setFormatter(formatter_json)  
   # http_handler.setLevel(logging.DEBUG)
   
    return logger

logger = custom_logger("http")
logger.exception("{'sample json message' : '2'}")

注釋用於測試,便於代碼的復制。

在上面的代碼片段中,文件處理程序完美地處理了 json 文件,但 HTTPHandler 沒有。 我嘗試按照鏈接中的指定創建一個 CustomHandler 原則上應該可以工作,但我無法弄清楚細節。

構造一個對“mapLogRecord”和“emit”方法進行更改的 CustomHandler 是否有意義?

最重要的是,獲取 JSON 格式的數據。

解決此問題的任何其他想法也可能會有所幫助!

好的,這是一個解決方案,它可以在服務器上以 JSON 格式登錄 output。 它使用自定義記錄器。 我還能夠格式化消息以使其適用。 下面的代碼給出了 json 格式的 output 並使用了請求模塊。

class RequestsHandler(logging.Handler):
    def emit(self, record):
        log_entry = self.format(record)
        return requests.post('http://localhost:3000/posts',
                             log_entry, headers={"Content-type": "application/json"}).content

class FormatterLogger(logging.Formatter):
    def __init__(self, task_name=None):
        
        super(FormatterLogger, self).__init__()

    def format(self, record):
        data = {'@message': record.msg,                
                 '@funcName' : record.funcName,
                 '@lineno' : record.lineno,
                 '@exc_info' : record.exc_info, 
                 '@exc_text' : record.exc_text,                 
                 }           

        return json.dumps(data)



def custom_logger(name):
    logger = logging.getLogger(name)
    custom_handler = RequestsHandler()
    formatter = FormatterLogger(logger)
    custom_handler.setFormatter(formatter)
    logger.addHandler(custom_handler)
    
    return logger


logger = custom_logger("http")
logger.exception("{'sample json message' : '2'}")

data 變量控制可以添加到消息中的參數。

output:

 {
      "@message": "{'sample json message' : '2'}",
      "@funcName": "<module>",
      "@lineno": 62,
      "@exc_info": [
        null,
        null,
        null
      ],
      "@exc_text": null,
      "id": 138
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM