【问题标题】:using python logging to the the existing script使用 python 记录到现有脚本
【发布时间】:2016-03-30 19:22:16
【问题描述】:

我有一个运行良好的 python 脚本链。我想要做的是使用 python 日志记录模块来记录我在这个脚本中的所有打印语句(忘记这个脚本的目的。我要做的就是添加日志记录功能来保存所有那些预期的打印语句显示在控制台上以登录到日志文件):

from __future__ import print_function
#import MySQLdb
import pymysql
import shutil
import os
import sys
import io
import string
import traceback
import time  
from watchdog.observers import Observer  
from watchdog.events import PatternMatchingEventHandler
from colorama import *
init()
# ==== FOR THE TRANSFORMATION SCRIPT ====
from datetime import tzinfo, timedelta, datetime
import pytz
import codecs
from pytz import timezone
import csv
# =======================================

if not os.path.exists('Archive'):
    os.mkdir("Archive")
if not os.path.exists('Failed'):
    os.mkdir("Failed")

class MyHandler(PatternMatchingEventHandler):
    patterns = ["*.csv","*.processing", "*.transforming","*.loading"]

    def process(self, event):
        """
        event.event_type 
            'modified' | 'created' | 'moved' | 'deleted'
        event.is_directory
            True | False
        event.src_path
            path/to/observed/file
        """
        eventFileName = event.src_path
        eventType = event.event_type
        if eventType == 'moved':
            eventFileName = event.dest_path
        fileNameWithPath, fileExtension = os.path.splitext(eventFileName)
        if fileExtension == '.csv':
            print (Back.GREEN +'Entering copier.py...'+ Style.RESET_ALL)
            execfile('./copier_MySQL.py')
        #if fileExtension == '.processing':
        #    print (Back.GREEN +'Entering parser_MySQL.py...'+ Style.RESET_ALL)
        #    execfile('./parser_MySQL.py')
        if fileExtension == '.processing': #change this to '.transforming' if the above parser_MySQL.py is uncommented
            t = time.time()
            print (Back.GREEN +'Entering transform_MySQL.py...'+ Style.RESET_ALL)
            execfile('./transform_MySQL.py')
            elapsed = time.time() - t
            print (Back.MAGENTA +'Time took to transform the file = '+str(elapsed)+ Style.RESET_ALL)
            print (Back.BLUE + "Exiting transform_MySQL.py..." + Style.RESET_ALL)
            print (Fore.YELLOW + "-----------#*#*#*-----------#*#*#*-----------" + Style.RESET_ALL)
        if fileExtension == '.loading':
            if os.path.isfile(eventFileName):
                t = time.time()
                print (Back.GREEN +'Entering sweeper.py...'+ Style.RESET_ALL)
                execfile('./sweeper_MySQL.py')
                elapsed = time.time() - t
                print (Back.MAGENTA +'Time took to load the file into database = '+str(elapsed-1)+ Style.RESET_ALL)
                print (Back.BLUE +"Disconnected from the MySQL server. Exiting sweeper.py..."+ Style.RESET_ALL)
                print (Fore.YELLOW+'-----------#*#*#*-----------#*#*#*-----------'+ Style.RESET_ALL)
            else:
                print (Fore.RED+eventFileName+' is not created by transform_MySQL.py. Check the above messages. NOT executing sweeper_MySQL.py'+ Style.RESET_ALL) 
    def on_moved(self, event):
        self.process(event)

    def on_created(self, event):
        self.process(event)

if __name__ == '__main__':
    observer = Observer()
    observer.schedule(MyHandler(), path='.')
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

我正在查看here 并尝试了一些方法,但无法在我的代码中完全适应该解决方案。非常感谢任何帮助。

【问题讨论】:

  • 为什么不直接将输出重定向到文件? myscript.py > myscript.log
  • @russdot 此脚本旨在在不受监控的计算机上运行,​​其中进度(那些打印语句)将打印到屏幕并将日志消息保存到文件中,所以 > myscript.log 是什么我真的希望我可以使用但不能。
  • @russdot 如果您在下面查看 xi_ 对他的回答的评论,他会链接到 python 的日志记录模块。所有这些功能都会自动添加到日志信息中,购买单行格式语句。手动执行此操作并写入日志文件将涉及多行代码,这有点重新发明轮子,这也是我使用 python 日志记录模块的另一个原因。
  • 很高兴您找到了可行的解决方案。您链接到的帖子描述了使用 python logging 模块记录到文件(尽管不像 xi_ 的答案那么简单),所以我认为您需要一个替代方案。

标签: python logging


【解决方案1】:

您可以使用logging 模块而不是一堆打印。

import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug(Back.GREEN +'Entering sweeper.py...'+ Style.RESET_ALL)

将输出保存到文件集:

logging.basicConfig(filename='myscript.log', level=logging.DEBUG)

【讨论】:

  • 这是我的想法,但它会将这些打印语句保存到文件中吗?
  • 我会尝试并返回。另外,我可以在该语句中使用多个级别,例如level=logging.DEBUG,logging.ERROR,logging.INFO 等吗?
  • 您可以使用不同级别的消息,更多信息请查看docs.python.org/2/howto/logging.html
  • 太棒了,这很有效,可以记录所有包括异常。 :-)
猜你喜欢
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多