source: ZMS/trunk/zmslog.py @ 1772

Revision 1772, 7.5 KB checked in by zmsdev, 5 months ago (diff)

applied minor performance-fixes (5): zms_log

Line 
1################################################################################
2# zmslog.py
3#
4# This program is free software; you can redistribute it and/or
5# modify it under the terms of the GNU General Public License
6# as published by the Free Software Foundation; either version 2
7# of the License, or (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program; if not, write to the Free Software
16# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17################################################################################
18
19# Imports.
20from App.special_dtml import HTMLFile
21import copy
22import logging
23import os
24import time
25import urllib
26# Product Imports.
27import ZMSItem
28import _fileutil
29
30
31def severity_string(severity, mapping={
32    logging.DEBUG:   'DEBUG',
33    logging.INFO:    'INFO',
34    logging.ERROR:   'ERROR',
35    }):
36    """Convert a severity code to a string."""
37    return mapping.get(int(severity), '')
38
39
40def log_time():
41  """Return a simple time string without spaces suitable for logging."""
42  return ("%4.4d-%2.2d-%2.2dT%2.2d:%2.2d:%2.2d"
43          % time.localtime()[:6])
44
45
46################################################################################
47###
48###   Class
49###
50################################################################################
51class ZMSLog(ZMSItem.ZMSItem):
52
53    # Properties.
54    # -----------
55    meta_type = 'ZMSLog'
56    icon = "misc_/zms/ZMSLog.gif"
57
58    # Management Options.
59    # -------------------
60    manage_options = (
61        { 'label': 'TAB_CONFIGURATION','action': '../manage_customize'},
62        )
63
64    # Management Interface.
65    # ---------------------
66    manage_main = HTMLFile( 'dtml/ZMSLog/manage_main', globals())
67    manage_remote = HTMLFile( 'dtml/ZMSLog/manage_remote', globals())
68
69    LOGGER = logging.getLogger("ZMS")
70
71    ############################################################################
72    #  ZMSLog.__init__:
73    #
74    #  Initialise a new instance of ZMSLog.
75    ############################################################################
76    def __init__(self, copy_to_stdout=False, logged_entries=[ 'ERROR']):
77      self.id = 'zms_log'
78      self.entries = []
79      self.keep_entries = 20
80      self.copy_to_zlog = True
81      self.copy_to_stdout = copy_to_stdout
82      self.logged_entries = logged_entries
83
84    ############################################################################
85    #  ZMSLog.setProperties:
86    #
87    #  Set properties.
88    ############################################################################
89    def setProperties(self, REQUEST, RESPONSE):
90      """ ZMSLog.setProperties """
91      self.keep_entries = REQUEST.get( 'keep_entries', 20)
92      self.copy_to_zlog = REQUEST.has_key( 'copy_to_zlog')
93      self.copy_to_stdout = REQUEST.has_key( 'copy_to_stdout')
94      self.logged_entries = REQUEST.get( 'logged_entries', [])
95      while len( self.entries) > self.keep_entries:
96        self.entries.remove( self.entries[-1])
97      return RESPONSE.redirect( REQUEST[ 'HTTP_REFERER'])
98
99    # --------------------------------------------------------------------------
100    #  ZMSLog.getLOG:
101    # --------------------------------------------------------------------------
102    def getLOG(self, REQUEST, RESPONSE):
103      """ ZMSLog.getLOG """
104      content_type = 'text/plain; charset=utf-8'
105      RESPONSE.setHeader('Content-Type',content_type)
106      RESPONSE.setHeader('Cache-Control', 'no-cache')
107      RESPONSE.setHeader('Pragma', 'no-cache')
108      return ''.join( map( lambda x: x+'\n', self.entries))
109
110    # --------------------------------------------------------------------------
111    #  ZMSLog.hasSeverity:
112    # --------------------------------------------------------------------------
113    def hasSeverity(self, severity):
114      return severity_string(severity) in self.logged_entries
115
116    # --------------------------------------------------------------------------
117    #  ZMSLog.LOG:
118    # --------------------------------------------------------------------------
119    def LOG(self, severity, info):
120      while len( self.entries) > self.keep_entries:
121        self.entries.remove( self.entries[-1])
122      self.entries.insert( 0 ,log_time() + ' ' + '%s(%i)'%(severity_string(severity),int(severity)) + '\n' + info)
123      self.entries = copy.copy(self.entries)
124      if getattr( self, 'copy_to_zlog', True):
125        self.LOGGER.log( severity, info)
126      if getattr( self, 'copy_to_stdout', True):
127        print log_time(), '%s(%i)'%(severity_string(severity),int(severity)), info
128
129    ############################################################################
130    ###
131    ###  Remote System
132    ###
133    ############################################################################
134
135    # --------------------------------------------------------------------------
136    #  ZMSLog.getPath
137    # --------------------------------------------------------------------------
138    def getPath(self, REQUEST):
139      path = SOFTWARE_HOME
140      if REQUEST.has_key('path'):
141        path = REQUEST['path']
142      return path
143
144    # --------------------------------------------------------------------------
145    #  ZMSLog.readDir
146    # --------------------------------------------------------------------------
147    def readDir(self, path):
148      return _fileutil.readDir( path)
149
150    # --------------------------------------------------------------------------
151    #  ZMSLog.getParentDir
152    # --------------------------------------------------------------------------
153    def getParentDir(self, path):
154      return _fileutil.getFilePath( path)
155
156
157    ############################################################################
158    #  ZMSLog.manage_index_html:
159    #
160    #  Display file.
161    ############################################################################
162    def manage_index_html(self, REQUEST, RESPONSE):
163      """ZMSLog.manage_index_html"""
164      path = self.getPath( REQUEST)
165      RESPONSE.setHeader( 'Content-Type','Unknown')
166      RESPONSE.setHeader( 'Content-Disposition','inline;filename="%s"'%_fileutil.extractFilename( path))
167      file = open( path, 'rb')
168      rtn = file.read()
169      file.close()
170      return rtn
171
172
173    ############################################################################
174    #  ZMSLog.manage_submit:
175    #
176    #  Submit action.
177    ############################################################################
178    def manage_submit(self, REQUEST, RESPONSE):
179      """ZMSLog.manage_submit"""
180     
181      path = self.getPath(REQUEST)
182      message = ""
183     
184      if REQUEST.get("btn") == "Execute":
185        command = REQUEST['command']
186        _fileutil.executeCommand(path,command)
187        message = "Command executed."
188       
189      elif REQUEST.get("btn") == "Upload":
190        obj = REQUEST['file']
191        type = 'b'
192        filename = "%s%s%s"%(path,os.sep,_fileutil.extractFilename(obj.filename))
193        _fileutil.exportObj( obj, filename, type)
194        message = "Upload complete."
195     
196      return REQUEST.RESPONSE.redirect( self.url_append_params( REQUEST[ 'HTTP_REFERER'], { 'manage_tabs_message' :message }))
197
198################################################################################
Note: See TracBrowser for help on using the repository browser.