【问题标题】:How to save logging info (info, debug, warning, error and critical) into a text file - Python如何将日志信息(信息、调试、警告、错误和关键)保存到文本文件中 - Python
【发布时间】:2017-06-27 15:41:34
【问题描述】:

如果目标文件是“C:\test\Logging\logging.txt”,我如何保存以下代码的日志记录信息?只要脚本运行就继续编写的想法。

import os
from threading import Timer
from os.path import isfile, join, exists
import shutil, time

PATH_TO_WATCH = "C:\\Test"

class FileReader:

    def __init__(self, path = None):
        self.path = path
        self.running = False
        self.timer = None

    def printFilesData(self, files):
        if self.path:
            timestamp = time.strftime("%d-%m-%Y-%H-%M-%S")
            destination = join(self.path, timestamp)
            for index, file in enumerate(files):
                if isfile(join(self.path, file)):
                    self.readAndMoveFile({"dest": destination, "name": file, "data": open(join(self.path, file))})

    def readAndMoveFile(self, fileData):

        print("\nArchivo:%s\n\n%s\n" % (fileData["name"], fileData["data"].read()))

        #El archivo debe ser cerrado para que se mueve
        fileData["data"].close()
        if not exists(fileData["dest"]):
            os.makedirs(fileData["dest"])
        try:
            shutil.move(join(self.path, fileData["name"]), fileData["dest"])
            print("\nArchivo \"%s\" movido \"%s\" a la carpeta.\n" % (fileData["name"], fileData["dest"]))
        except WindowsError as e:
            print(e)

    def listFiles(self):
        if self.path:
            return [file for file in os.listdir(self.path)]
        return None

    def stopWatching(self):
        print("\nNot watching.\n")
        self.timer.cancel()

    def complete(self):
        after = self.listFiles()
        added = [file for file in after if not file in self.lock]
        self.printFilesData(added)
        self.lock = after
        self.timer = Timer(5.0, self.complete)
        self.timer.start()

    def startWatching(self):
        if(self.path):
            self.lock = self.listFiles()
            print("\nDirectorio que se esta observando %s...\n" % self.path)
            self.printFilesData(self.lock)
            self.timer = Timer(5.0, self.complete)
            self.timer.start()
        else: print("Ruta sin definir.")

class Main():

    def __init__(self):
        self.reader = FileReader("C:\\Test")
        self.reader.startWatching()


if __name__ == '__main__':        
    Main()

我知道我必须添加导入日志,并且:

logging.debug()
logging.info()
logging.warning()
logging.error()
logging.critical()

但我不知道如何申请或将它们放在哪里

【问题讨论】:

  • 欢迎来到 StackOverflow,请花点时间查看导览:stackoverflow.com/tour,如何创建最小、完整和可验证的示例:stackoverflow.com/help/mcve,更具体地说,如何提出好问题 stackoverflow.com/help/how-to-ask - 如果您在向 SO 寻求帮助之前对您的问题进行一些思考,并在代码中包含特定问题您将获得更好的反馈和有用的答案我尝试过努力自己解决问题。

标签: python file logging netbeans


【解决方案1】:

有一个带有一些示例的文档可以指导您how the logging could be used in python

如需快速入门,请参见以下示例,该示例将输出写入文件“logging.txt”

import logging
logging.basicConfig(filename='logging.txt')
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.error('this is an error')
logger.info('this is an info')

文件中的输出将是

ERROR:__main__:this is an error
INFO:__main__:this is an info

因此,如果需要,您可以将 logger.info ... 放置在脚本中的任何位置。

【讨论】:

  • 知道了。但是我如何指定路径/​​路径将在哪里创建带有日志的文件名?因为我的脚本所做的是每次在目录中移动或创建新文件时,它都会创建一个新文件夹,并且该文件将被移动到最近创建的文件夹中。这就是我将 logging.txt 放在名为“Logging”的文件夹中的原因。
  • @Beta 您可以将路径添加到filename 的配置中,即logging.basicConfig(filename='Logging/logging.txt')
  • 你的意思是它应该像这样 "C:\test\Logging\logging.txt" ?
  • @Beta 是的。
猜你喜欢
  • 2023-03-06
  • 2020-12-07
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-14
相关资源
最近更新 更多