首页 > 解决方案 > 使用 Python Logging 模块将日志保存到 S3,如何捕获所有模块的所有级别的日志?

问题描述

这是我第一次在 Python(3.7) 中使用日志记录模块。我的代码使用导入的模块,这些模块也有自己的日志语句。当我第一次在我的代码中添加日志语句时,我没有使用 getLogger()。我只是使用logging.basicConfig(filename)并直接调用logger.debug()来记录语句。当我这样做时,我的脚本和所有导入的模块中的所有日志都会一起输出到同一个文件中。

现在我需要转换我的代码以将日志保存到 s3 而不是文件。我尝试了如何在不先写入标准输出的情况下将日志从内存直接写入 AWS S3中提到的解决方案?(Python,boto3) - 堆栈溢出,但我有两个问题:

  1. 当我检查 s3 时,输出中不存在任何“前缀”。
  2. 仅显示 INFO 语句。我的印象是logging.basicConfig(level=logging.INFO)它会输出 INFO 级别或更高级别的所有日志,但我只看到 INFO。此外,在所有级别之前,只有 INFO 日志会打印到标准输出。我不知道为什么缺少“前缀”。

from psaw import PushshiftAPI
api = PushshiftAPI()
import time
import logging
import boto3
import io
import atexit

def write_logs(body, bucket, key):
    s3 = boto3.client("s3")
    s3.put_object(Body=body.getvalue(), Bucket=bucket, Key=key)

logging.basicConfig(level=logging.INFO)
log = logging.getLogger()
log_stringio = io.StringIO()
handler = logging.StreamHandler(log_stringio)
log.addHandler(handler)

def collectRange(sub,start,end):
    atexit.register(write_logs, body=log_stringio, bucket="<...>", key=f'{sub}/log.txt')
    s3 = boto3.resource('s3')
    object = s3.Object('<...>', f'{sub}/{sub}@{start}-{end}.csv')
    now = time.time()
    logging.info(f'Start Time:{now}')
    logging.debug('First request')
    gen = api.search_comments(after=start, before=end,<...>, subreddit=sub)
    r=next(gen)
    <...>
    quit()

输出:

Found credentials in shared credentials file: ~/.aws/credentials
Start Time:1591310443.7060978
https://api.pushshift.io/reddit/comment/search?<...>
https://api.pushshift.io/reddit/comment/search?<...>

期望的输出:

INFO:botocore.credentials:Found credentials in shared credentials file: ~/.aws/credentials
INFO:root:Start Time:1591310443.7060978
DEBUG:root:First request
INFO:psaw.PushshiftAPI:https://api.pushshift.io/reddit/comment/search?<...>
DEBUG:psaw.PushshiftAPI:<whatever is usually here>
DEBUG:psaw.PushshiftAPI:<whatever is usually here>
INFO:psaw.PushshiftAPI:https://api.pushshift.io/reddit/comment/search?<...>
DEBUG:psaw.PushshiftAPI:<whatever is usually here>
DEBUG:psaw.PushshiftAPI:<whatever is usually here>

任何帮助表示赞赏。谢谢。

标签: pythonpython-3.xamazon-web-servicesamazon-s3logging

解决方案


推荐阅读