如何将日志信息(信息,调试,警告,错误和严重)保存到文本文件中 - Python

时间:2017-06-27 15:41:35

标签: python file logging netbeans

如果目标文件是" 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()

但我不知道如何申请或在哪里申请

1 个答案:

答案 0 :(得分:2)

有一些文档可以为您提供一些示例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 ...放在脚本的任何位置。