【问题标题】:How to create log file and save all the running logs from Python script如何从 Python 脚本创建日志文件并保存所有运行日志
【发布时间】:2021-09-02 08:40:26
【问题描述】:

我有以下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))

【问题讨论】:

标签: python logging python-3.7 logfile


【解决方案1】:

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

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 指出的,应该使用一些日志模块来写入文件。

【讨论】:

  • 我收到错误:log_msg = t.strftime("[%d.%m.%y] Time: %H:%M:%S - ") + msg TypeError: can only concatenate str(不是“int”)到 str
  • 尝试将 t.strftime 转换为 str `log_msg = str(t.strftime(...))
  • 更新了代码,有一些括号不匹配
  • 这是一个非常幼稚的解决方案,应该使用内置的日志模块或第三方日志包的数量。
  • 仍然出现错误:log_msg = str(t.strftime("[%d.%m.%y] Time: %H:%M:%S - ")) + msg TypeError: can仅将 str(不是“int”)连接到 str
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
  • 2019-12-12
  • 1970-01-01
相关资源
最近更新 更多