← Back to team overview

openerp-dev-web team mailing list archive

lp:~openerp-dev/openobject-client/trunk-add-datetime-in-logfile-rga into lp:openobject-client

 

Ravi Gadhia (OpenERP) has proposed merging lp:~openerp-dev/openobject-client/trunk-add-datetime-in-logfile-rga into lp:openobject-client.

Requested reviews:
  Naresh(OpenERP) (nch-openerp)

For more details, see:
https://code.launchpad.net/~openerp-dev/openobject-client/trunk-add-datetime-in-logfile-rga/+merge/53964

Hello sir
as you said I added new option:
                                -w --write_to_config     save configuration to ~/.

and solved other problems like garbage value store in log , logrotate argurments, etc

Thanks 





-- 
https://code.launchpad.net/~openerp-dev/openobject-client/trunk-add-datetime-in-logfile-rga/+merge/53964
Your team OpenERP R&D Team is subscribed to branch lp:~openerp-dev/openobject-client/trunk-add-datetime-in-logfile-rga.
=== added file 'bin/loglevel.py'
--- bin/loglevel.py	1970-01-01 00:00:00 +0000
+++ bin/loglevel.py	2011-03-18 09:43:27 +0000
@@ -0,0 +1,110 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+#    OpenERP, Open Source Management Solution
+#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
+#    Copyright (C) 2010-2011 OpenERP s.a. (<http://openerp.com>).
+#
+#    This program is free software: you can redistribute it and/or modify
+#    it under the terms of the GNU Affero General Public License as
+#    published by the Free Software Foundation, either version 3 of the
+#    License, or (at your option) any later version.
+#
+#    This program is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#    GNU Affero General Public License for more details.
+#
+#    You should have received a copy of the GNU Affero General Public License
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+##############################################################################
+import logging
+import logging.handlers
+import sys
+import options
+import release
+
+BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, _NOTHING, DEFAULT = range(10)
+#The background is set with 40 plus the number of the color, and the foreground with 30
+#These are the sequences need to get colored ouput
+RESET_SEQ = "\033[0m"
+COLOR_SEQ = "\033[1;%dm"
+BOLD_SEQ = "\033[1m"
+COLOR_PATTERN = "%s%s%%s%s" % (COLOR_SEQ, COLOR_SEQ, RESET_SEQ)
+
+logging.DEBUG_RPC = logging.DEBUG - 1
+logging.addLevelName(logging.DEBUG_RPC, 'DEBUG_RPC')
+logging.Logger.debug_rpc = lambda self, msg, *args, **kwargs: self.log(logging.DEBUG_RPC, msg, *args, **kwargs)
+
+logging.DEBUG_RPC_ANSWER = logging.DEBUG - 2
+logging.addLevelName(logging.DEBUG_RPC_ANSWER, 'DEBUG_RPC_ANSWER')
+logging.Logger.debug_rpc_answer = lambda self, msg, *args, **kwargs: self.log(logging.DEBUG_RPC_ANSWER, msg, *args, **kwargs)
+
+LEVEL_COLOR_MAPPING = {
+    logging.DEBUG: (BLUE, DEFAULT),
+    logging.INFO: (GREEN, DEFAULT),
+    logging.WARNING: (YELLOW, DEFAULT),
+    logging.ERROR: (RED, DEFAULT),
+    logging.CRITICAL: (WHITE, RED),
+    logging.DEBUG_RPC: (BLUE, WHITE),
+    logging.DEBUG_RPC_ANSWER: (BLUE, WHITE),
+}
+
+DB = '?'
+
+
+class DBFormatter(logging.Formatter):
+    def format(self, record):
+        record.dbname = DB
+        return logging.Formatter.format(self, record)
+
+class ColoredFormatter(DBFormatter):
+    def format(self, record):
+        fg_color, bg_color = LEVEL_COLOR_MAPPING[record.levelno]
+        record.levelname = COLOR_PATTERN % (30 + fg_color, 40 + bg_color, record.levelname)
+        return DBFormatter.format(self, record)
+
+def init_logger():
+    import os
+    # create a format for log messages and dates
+    format = '[%(asctime)s][%(dbname)s] %(levelname)s:%(name)s:%(message)s'
+    # add new log levels below DEBUG
+    if options.options['logging.syslog']:
+        # SysLog Handler
+        if os.name == 'nt':
+            handler = logging.handlers.NTEventLogHandler("%s %s" % (release.description, release.version))
+        else:
+            handler = logging.handlers.SysLogHandler('/dev/log')
+        format = '%s %s' % (release.description, release.version) \
+                + ':[%(dbname)s]:%(levelname)s:%(name)s:%(message)s'
+                
+    elif options.options['logging.logfile']:
+        # LogFile Handler
+        logf = options.options['logging.logfile']
+        try:
+            dirname = os.path.dirname(logf)
+            if dirname and not os.path.isdir(dirname):
+                os.makedirs(dirname)
+            if options.options['logging.logrotate'] is not False:
+                handler = logging.handlers.TimedRotatingFileHandler(logf,'D',1,30)
+            elif os.name == 'posix':
+                handler = logging.handlers.WatchedFileHandler(logf)
+            else:
+                handler = logging.FileHandler(logf)
+        except Exception, e:
+            sys.stderr.write("ERROR: couldn't create the logfile directory. Logging to the standard output.\n")
+            handler = logging.StreamHandler(sys.stdout)
+    else:
+        # Normal Handler on standard output
+        handler = logging.StreamHandler(sys.stdout)
+    if isinstance(handler, logging.StreamHandler) and not isinstance(handler, logging.handlers.TimedRotatingFileHandler) and getattr(handler.stream, 'isatty', None):
+        formatter = ColoredFormatter(format)
+    else:
+        formatter = DBFormatter(format)
+    handler.setFormatter(formatter)
+
+    # add the handler to the root logger
+    logger = logging.getLogger()
+    logger.handlers = []
+    logger.addHandler(handler)

=== modified file 'bin/openerp-client.py'
--- bin/openerp-client.py	2011-01-17 19:11:21 +0000
+++ bin/openerp-client.py	2011-03-18 09:43:27 +0000
@@ -33,6 +33,14 @@
 
 import sys
 import os
+IS_USING_PY2EXE = hasattr(sys, "frozen")
+if IS_USING_PY2EXE:
+    # Redirect log to a file.
+    LOG_FILENAME = os.path.join(os.getcwd(), "openerp-client.log")
+    logFile = open(os.path.join(LOG_FILENAME), "w")
+    sys.stderr = logFile
+    sys.stdout = logFile
+    
 import release
 __author__ = release.author
 __version__ = release.version
@@ -41,12 +49,6 @@
 __builtin__.__dict__['openerp_version'] = __version__
 
 import logging
-arguments = {}
-if sys.platform == 'win32':
-    arguments['filename'] = os.path.join(os.environ['USERPROFILE'], 'openerp-client.log')
-
-logging.basicConfig(**arguments)
-
 from distutils.sysconfig import get_python_lib
 terp_path = os.path.join(get_python_lib(), 'openerp-client')
 sys.path.append(terp_path)
@@ -79,6 +81,8 @@
 translate.setlang()
 
 import options
+from loglevel import init_logger
+init_logger()
 
 # On first run, client won't have a language option,
 # so try with the LANG environ, or fallback to english
@@ -86,22 +90,9 @@
 if not client_lang:
     client_lang = os.environ.get('LANG', '').split('.')[0]
 
+
 translate.setlang(client_lang)
 
-
-# add new log levels below DEBUG
-logging.DEBUG_RPC = logging.DEBUG - 1
-logging.addLevelName(logging.DEBUG_RPC, 'DEBUG_RPC')
-logging.Logger.debug_rpc = lambda self, msg, *args, **kwargs: self.log(logging.DEBUG_RPC, msg, *args, **kwargs)
-
-logging.DEBUG_RPC_ANSWER = logging.DEBUG - 2
-logging.addLevelName(logging.DEBUG_RPC_ANSWER, 'DEBUG_RPC_ANSWER')
-logging.Logger.debug_rpc_answer = lambda self, msg, *args, **kwargs: self.log(logging.DEBUG_RPC_ANSWER, msg, *args, **kwargs)
-
-logging.getLogger().setLevel(getattr(logging, options.options['logging.level'].upper()))
-
-
-
 import modules
 import common
 

=== modified file 'bin/options.py'
--- bin/options.py	2011-01-16 17:39:47 +0000
+++ bin/options.py	2011-03-18 09:43:27 +0000
@@ -26,6 +26,8 @@
 import gtk
 import gettext
 import release
+import logging
+import loglevel
 
 def get_home_dir():
     """Return the closest possible equivalent to a 'home' directory.
@@ -101,6 +103,9 @@
             'printer.softpath_html': 'none',
             'printer.path': 'none',
             'logging.level': 'INFO',
+            'logging.logfile': None,
+            'logging.logrotate': True,
+            'logging.syslog':None,
             'logging.output': 'stdout',
             'debug_mode_tooltips':False,
             'client.default_path': os.path.expanduser('~'),
@@ -121,26 +126,41 @@
         parser = optparse.OptionParser(version=_("OpenERP Client %s" % openerp_version))
         parser.add_option("-c", "--config", dest="config",help=_("specify alternate config file"))
         parser.add_option("-v", "--verbose", dest="log_level", action='store_const', const="debug", help=_("Enable basic debugging. Alias for '--log-level=debug'"))
-        parser.add_option("-l", "--log-level", dest="log_level", type='choice', choices=loglevels, default='error', help=_("specify the log level: %s") % ", ".join(loglevels))
+        parser.add_option("-l", "--log-level", dest="log_level", type='choice', choices=loglevels, help=_("specify the log level: %s") % ", ".join(loglevels))
+        parser.add_option("--logfile", dest="logfile", help="file where the client log will be stored")
+        parser.add_option("--no-logrotate", dest="logrotate", action="store_false",
+                         help="do not rotate the logfile")
+        parser.add_option("--syslog", action="store_true", dest="syslog",
+                         default=False, help="Send the log to the syslog server")
         parser.add_option("-u", "--user", dest="login", help=_("specify the user login"))
         parser.add_option("-p", "--port", dest="port", help=_("specify the server port"))
         parser.add_option("-s", "--server", dest="server", help=_("specify the server ip/name"))
+        parser.add_option("-w", "--write_to_config", dest="write_to_config", action="store_true", help=_("Save configuration to ~/.openerprc"))
         (opt, args) = parser.parse_args()
-
+        self.write_to_config = opt.write_to_config
         self.rcfile = self._get_rcfile(fname, opt.config)
         self.load()
-
-        self.options['logging.level'] = opt.log_level
-
         for arg in ('login', 'port', 'server'):
             if getattr(opt, arg):
                 self.options['login.'+arg] = getattr(opt, arg)
-
+                
+        for arg in ('syslog', 'logrotate', 'logfile', 'log_level'):
+            if getattr(opt, arg):
+                self.options['logging.'+ arg] =  getattr(opt, arg)
+        
+        
+        self.change_loglevel()
+                
+    def change_loglevel(self):
+        logging.getLogger().setLevel(getattr(logging, self.options.get('logging.log_level','info').upper()))
+      
     def _get_rcfile(self, fname, optconfigfile):
         rcfile = fname or optconfigfile or os.environ.get('OPENERPRC') or os.path.join(get_home_dir(), '.openerprc')
         if not os.path.exists(rcfile):
             import logging
             log = logging.getLogger('common.options')
+            handler = logging.StreamHandler(sys.stdout)
+            log.addHandler(handler)
             additional_info = ""
             if optconfigfile:
                 additional_info = " Be sure to specify an absolute path name if you are using the '-c' command line switch"
@@ -149,16 +169,17 @@
 
     def save(self, fname = None):
         try:
-            p = ConfigParser.ConfigParser()
-            sections = {}
-            for o in self.options.keys():
-                if not len(o.split('.'))==2:
-                    continue
-                osection,oname = o.split('.')
-                if not p.has_section(osection):
-                    p.add_section(osection)
-                p.set(osection,oname,self.options[o])
-            p.write(file(self.rcfile,'wb'))
+            if self.write_to_config or not os.path.isfile(self.rcfile):
+                p = ConfigParser.ConfigParser()
+                sections = {}
+                for o in self.options.keys():
+                    if not len(o.split('.'))==2:
+                        continue
+                    osection,oname = o.split('.')
+                    if not p.has_section(osection):
+                        p.add_section(osection)
+                    p.set(osection,oname,self.options[o])
+                p.write(file(self.rcfile,'wb'))
         except:
             import logging
             log = logging.getLogger('common.options')
@@ -202,6 +223,5 @@
 
 options = configmanager()
 
-
 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
 

=== modified file 'bin/rpc.py'
--- bin/rpc.py	2011-01-06 09:49:16 +0000
+++ bin/rpc.py	2011-03-18 09:43:27 +0000
@@ -25,6 +25,7 @@
 import socket
 
 import tiny_socket
+import loglevel
 import service
 import common
 import options
@@ -252,6 +253,7 @@
         # exception raised?
         sock = self._gw(self._url, self.db, self.uid, self._passwd)
         self.context_reload()
+        loglevel.DB = self.db
         return 1
 
     def migrate_databases(self, url, password, databases):


Follow ups