Python logging into file as a dictionary or JSON

前端 未结 2 1640
醉梦人生
醉梦人生 2021-01-04 13:17

I am trying to set up logging where I can log in both stdout and on to a file. This i have accomplished using the following code:

logging.basicConfig(
              


        
2条回答
  •  醉话见心
    2021-01-04 13:55

    So based on @abarnert, i found this Link which provided a good path to making this concept work for the most part. The code as it stands is:

    logger=logging.getLogger()
    logger.setLevel(logging.DEBUG)
    
    file_handler=logging.FileHandler('foo.log')
    stream_handler=logging.StreamHandler()
    
    stream_formatter=logging.Formatter(
        '%(asctime)-15s %(levelname)-8s %(message)s')
    file_formatter=logging.Formatter(
        "{'time':'%(asctime)s', 'name': '%(name)s', \
        'level': '%(levelname)s', 'message': '%(message)s'}"
    )
    
    file_handler.setFormatter(file_formatter)
    stream_handler.setFormatter(stream_formatter)
    
    logger.addHandler(file_handler)
    logger.addHandler(stream_handler)
    

    Although it does not fully meet the requirement, it doesnt require any pre processing, and allows me to create two log handlers.

    Afterwards, i can use something like:

    with open('foo.log') as f:
        logs = f.read().splitlines()
    for l in logs:
        for key, value in eval(l):
            do something ...
    

    to pull dict objects instead of fighting with improperly formatted JSON to accomplish what i had set out to accomplish.

    Still am hoping for a more elegant solution.

提交回复
热议问题