如何创建日志文件并保存来自 Python 脚本的所有 运行 日志

How to create log file and save all the running logs from Python script

我有以下部分 Python 代码 extraction.py,其中有很多 print 语句,还有其他日志是从 REST API 生成的。我想创建带有日志文件附加日期和时间前缀的日志文件,例如 log_yyyy-MM-dd-hhminss 以跟踪来自我的 Python 代码的所有日志。这将有助于跟踪我的 Python 代码的每日日志。

import requests
import json
import shutil
import time
import gzip
import os

extraction request:
if status_code == 202:
    requestUrl = r2.headers["location"]
    print('Extraction is not complete, we shall poll the location URL:')
    print(str(requestUrl))

    requestHeaders = {
        "Prefer": "respond-async",
        "Content-Type": "application/json",
        "Authorization": "token " + token
    }

while (status_code == 202):
    print('As we received a 202, we wait 30 seconds, then poll again (until we receive a 200)')
    time.sleep(30)
    r3 = requests.get(requestUrl, headers=requestHeaders)
    status_code = r3.status_code
    print('HTTP status of the response: ' + str(status_code))

您可以创建一个函数来为您执行此操作并用它替换打印件。 大致如下:

def log(msg):
    t = datetime.datetime.now()
    time = t.strftime("[%d.%m.%y] Time - %H_%M_%S")
    log_msg = str(msg)
    # or any other format (could even use time.ctime() or similar)
    print(log_msg)
    with open("path/" + time + ".log",'a+') as file:
        file.write(log_msg + "\n")

所以你的代码看起来像这样:

import requests
import json
import shutil
import time
import gzip
import os
import datetime
def log(msg):
    t = datetime.datetime.now()
    time = t.strftime("[%d.%m.%y] Time - %H_%M_%S")
    log_msg = str(msg)
    print(log_msg)
    with open("path/" + time + ".log",'a+') as file:
        file.write(log_msg + "\n")


extraction request:
if status_code == 202:
    requestUrl = r2.headers["location"]
    log('Extraction is not complete, we shall poll the location URL:')
    log(str(requestUrl))

    requestHeaders = {
        "Prefer": "respond-async",
        "Content-Type": "application/json",
        "Authorization": "token " + token
    }

while (status_code == 202):
    log('As we received a 202, we wait 30 seconds, then poll again (until we receive a 200)')
    time.sleep(30)
    r3 = requests.get(requestUrl, headers=requestHeaders)
    status_code = r3.status_code
    log('HTTP status of the response: ' + str(status_code))

另外正如 buran 所指出的,应该使用一些日志记录模块来写入文件。