【问题标题】:Logging Linux Terminal Output to Files by Date?按日期将 Linux 终端输出记录到文件中?
【发布时间】:2019-06-06 16:41:21
【问题描述】:

我有兴趣创建或使用一种方法将我的 python 脚本的所有终端输出记录到日志文件中,但我希望日志在每个新的一天开始时自动启动一个新文件。到目前为止,我知道我可以编写一个 shell 脚本来执行以下操作:

script test.txt 
python -yourscriptnamehere-

但是我有兴趣让这个脚本成为脚本可以结束录制的东西,并在新的一天开始新的录制,使用新的文件名,最好使用日期作为日志名称。

这可行吗?如果可行,我会从哪里开始?

注意:我不只是将所有打印记录到 python 脚本中的文件的原因是因为我正在使用日志记录库来获取与服务器连接的调试信息,而我似乎没有控制该过程。

【问题讨论】:

  • 您无法控制 your python 脚本中的日志库?我能想到的两种最简单的方法是使用日志库每天(从您的脚本中)创建新日志,或者使用journalctl 来捕获脚本输出和日期(可能需要 root,我得查一下)。

标签: linux python-3.x shell logging


【解决方案1】:

目标:使用 python 将脚本的所有终端输出记录到日志文件中。

解决方案:在记录之前,检查今天的日期,如果今天的文件存在,则写在那里,如果不存在,则创建一个。

import time    
import sys
import os
import subprocess

logDir = "log/"        //Create a log dir beforehand
p = subprocess.Popen("[script you want to log]", stdout=subprocess.PIPE)  //Specify the script you want to log
while 1:
  line = p.stdout.readline() // read stdout line by line
  today = time.strftime("%d-%m-%Y") // get today's date
  filePath = logDir + today // file path as log dir + today's date
  if os.path.isfile(filePath): // if file exists
    with open(filePath, "a") as logFile: write at the end of the file
      logFile.write(line)
  else:    // if file does not exist
    logFile = open(filePath, "w") // create a new file 
    logFile.write(line) // write

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2016-07-26
    相关资源
    最近更新 更多