From e4a14199d57455083e71f7b68b78fc231d32fc77 Mon Sep 17 00:00:00 2001 From: bai Date: Tue, 28 Jul 2020 04:28:12 -0400 Subject: Usando logging correcto de Python --- cgi/framework.py | 43 ++----------------------------------------- cgi/img.py | 8 ++++++-- cgi/post.py | 9 +++++---- cgi/weabot.py | 15 ++++++--------- 4 files changed, 19 insertions(+), 56 deletions(-) diff --git a/cgi/framework.py b/cgi/framework.py index 5f95303..8c39f81 100644 --- a/cgi/framework.py +++ b/cgi/framework.py @@ -9,6 +9,7 @@ import socket import _mysql import urllib import re +import logging from Cookie import SimpleCookie from settings import Settings @@ -22,7 +23,7 @@ def setBoard(dir): """ if not dir: raise UserError, _("The specified board is invalid.") - logTime("Seteando el board " + dir) + logging.debug("Seteando el board " + dir) board = FetchOne( "SELECT * FROM `boards` WHERE `dir` = '%s' LIMIT 1" % _mysql.escape_string(dir)) if not board: @@ -32,7 +33,6 @@ def setBoard(dir): "SELECT * FROM `boards_filetypes` INNER JOIN `filetypes` ON filetypes.id = boards_filetypes.filetypeid WHERE `boardid` = %s ORDER BY `ext` ASC" % _mysql.escape_string(board['id'])) board["filetypes_ext"] = [filetype['ext'] for filetype in board['filetypes']] - logTime("Board seteado.") Settings._.BOARD = board @@ -474,42 +474,3 @@ def send_mail(subject, srcmsg): s.sendmail(me, [you], msg.as_string()) s.quit() - -class weabotLogger: - def __init__(self): - self.times = [] - - def log(self, message): - self.times.append([time.time(), message]) - - def allTimes(self): - output = "Time Logged action\n--------------------------\n" - start = self.times[0][0] - for time in self.times: - difference = str(time[0] - start) - difference_split = difference.split(".") - if len(difference_split[0]) < 2: - difference_split[0] = "0" + difference_split[0] - - if len(difference_split[1]) < 7: - difference_split[1] = ( - "0" * (7 - len(difference_split[1]))) + difference_split[1] - elif len(difference_split[1]) > 7: - difference_split[1] = difference_split[1][:7] - - output += ".".join(difference_split) + " " + time[1] + "\n" - - return output - - -logger = weabotLogger() - - -def logTime(message): - global logger - logger.log(message) - - -def logTimes(): - global logger - return logger.allTimes() diff --git a/cgi/img.py b/cgi/img.py index 73bbdc7..ff7cd74 100644 --- a/cgi/img.py +++ b/cgi/img.py @@ -4,6 +4,7 @@ import math #import random import os import subprocess +import logging from StringIO import StringIO from settings import Settings @@ -92,7 +93,7 @@ def processImage(post, data, t, originalname, spoiler=False): if used_filetype['ffmpeg_thumb'] == '1': # use ffmpeg to make thumbnail - logTime("Generating thumbnail") + logging.debug("Generating thumbnail") if used_filetype['mime'][:5] == 'video': # Create preview for video AND spoiler it if necessary @@ -112,6 +113,7 @@ def processImage(post, data, t, originalname, spoiler=False): "-quality", str(Settings.THUMB_QUALITY), file_thumb_path]) except subprocess.CalledProcessError, e: os.remove(file_path) + logging.error("Thumbnail creation failure: " + e.output) raise UserError, _("Thumbnail creation failure.") + ' ('+str(e.returncode)+')' elif used_filetype['mime'][:5] == 'audio': # we do an exception and use png for audio waveform thumbnails since they @@ -135,6 +137,7 @@ def processImage(post, data, t, originalname, spoiler=False): '-frames:v', '1', '-threads', '1', file_thumb_path]) except subprocess.CalledProcessError, e: os.remove(file_path) + logging.error("Thumbnail creation failure: " + e.output) raise UserError, _("Thumbnail creation failure.") + ' ('+str(e.returncode)+')' else: # use imagemagick to make thumbnail @@ -146,11 +149,12 @@ def processImage(post, data, t, originalname, spoiler=False): args += ["-quality", str(Settings.THUMB_QUALITY), file_thumb_path] # generate thumbnails - logTime("Generating thumbnail") + logging.debug("Generating thumbnail") try: subprocess.check_output(args) except subprocess.CalledProcessError, e: os.remove(file_path) + logging.error("Thumbnail creation failure: " + repr(e.output)) raise UserError, _("Thumbnail creation failure.") + ' ('+str(e.returncode)+')' # check if thumbnail was truly created diff --git a/cgi/post.py b/cgi/post.py index da2ad47..e27b971 100644 --- a/cgi/post.py +++ b/cgi/post.py @@ -7,6 +7,7 @@ import threading import Queue import _mysql import formatting +import logging from database import * from template import * @@ -49,7 +50,7 @@ class Post(object): return self.post def insert(self): - logTime("Insertando Post") + logging.info("Insertando Post") post_values = [] for key, value in self.post.iteritems(): @@ -715,7 +716,7 @@ def deletePost(postid, password, deltype='0', imageonly=False, quick=False): if int(post["parentid"]) == 0: deleteReplies(post) - logTime("Deleting post " + str(postid)) + logging.info("Deleting post " + str(postid)) if deltype != '0' and post["parentid"] != '0': # Soft delete (recycle bin) UpdateDb("UPDATE `posts` SET `IS_DELETED` = %s WHERE `boardid` = %s AND `id` = %s LIMIT 1" % (deltype, board["id"], post["id"])) @@ -788,7 +789,7 @@ def trimThreads(): """ Delete any threads which have passed the MAX_THREADS setting """ - logTime("Trimming threads") + logging.debug("Trimming threads") board = Settings._.BOARD archived = False @@ -1026,7 +1027,7 @@ def regenerateHome(): """ Update index.html in the boards directory with useful data for users """ - logTime("Updating home") + logging.debug("Updating home") t = datetime.datetime.now() limit = Settings.HOME_LASTPOSTS diff --git a/cgi/weabot.py b/cgi/weabot.py index 3c5d0f5..ff93118 100755 --- a/cgi/weabot.py +++ b/cgi/weabot.py @@ -8,6 +8,7 @@ import time import datetime import random import cgi +import logging import _mysql from Cookie import SimpleCookie @@ -33,6 +34,9 @@ _LOG = False class weabot(object): def __init__(self, environ, start_response): global _DEBUG + + logging.basicConfig(filename='weabot.log', format='%(asctime)s %(levelname)s %(message)s', level=logging.DEBUG) + self.environ = environ if self.environ["PATH_INFO"].startswith("/weabot.py/"): self.environ["PATH_INFO"] = self.environ["PATH_INFO"][11:] @@ -48,7 +52,6 @@ class weabot(object): 'weabot', './locale', languages=[Settings.LANG]) lang.install() - logTime("**Start**") if _DEBUG: import cProfile @@ -70,12 +73,6 @@ class weabot(object): # close database and finish CloseDb() - logTime("**End**") - - if _LOG: - logfile = open(Settings.ROOT_DIR + "weabot.txt", "w") - logfile.write(logTimes()) - logfile.close() def __iter__(self): self.handleResponse() @@ -812,7 +809,7 @@ class weabot(object): post["message"]), _mysql.escape_string(board["id"]), _mysql.escape_string(str(postid)))) # do operations if replying to a thread (bump, autoclose, update cache) - logTime("Updating thread") + logging.debug("Updating thread") thread_length = None if post["parentid"]: # get length of the thread @@ -1086,7 +1083,7 @@ if __name__ == "__main__": # Psyco is not required, however it will be used if available try: import psyco - logTime("Psyco se ha instalado") + logging.debug("Psyco se ha instalado") psyco.bind(tenjin.helpers.to_str) psyco.bind(weabot.run, 2) psyco.bind(getFormData) -- cgit v1.2.1-18-gbd029