Home | Trees | Indices | Help |
---|
|
1 # Software License Agreement (BSD License) 2 # 3 # Copyright (c) 2008, Willow Garage, Inc. 4 # All rights reserved. 5 # 6 # Redistribution and use in source and binary forms, with or without 7 # modification, are permitted provided that the following conditions 8 # are met: 9 # 10 # * Redistributions of source code must retain the above copyright 11 # notice, this list of conditions and the following disclaimer. 12 # * Redistributions in binary form must reproduce the above 13 # copyright notice, this list of conditions and the following 14 # disclaimer in the documentation and/or other materials provided 15 # with the distribution. 16 # * Neither the name of Willow Garage, Inc. nor the names of its 17 # contributors may be used to endorse or promote products derived 18 # from this software without specific prior written permission. 19 # 20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 24 # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 27 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 28 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 30 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 31 # POSSIBILITY OF SUCH DAMAGE. 32 33 """ 34 Library for configuring python logging to standard ROS locations (e.g. ROS_LOG_DIR). 35 """ 36 37 import os 38 import sys 39 import time 40 import logging 41 import logging.config 42 43 import rospkg 44 from rospkg.environment import ROS_LOG_DIR 45 4749 log_dir = os.path.dirname(logfile_dir) 50 latest_dir = os.path.join(log_dir, 'latest') 51 if os.path.lexists(latest_dir): 52 if not os.path.islink(latest_dir): 53 return False 54 os.remove(latest_dir) 55 os.symlink(logfile_dir, latest_dir) 56 return True5759 """ 60 Configure Python logging package to send log files to ROS-specific log directory 61 :param logname str: name of logger, ``str`` 62 :param filename: filename to log to. If not set, a log filename 63 will be generated using logname, ``str`` 64 :param env: override os.environ dictionary, ``dict`` 65 :returns: log file name, ``str`` 66 :raises: :exc:`LoggingException` If logging cannot be configured as specified 67 """ 68 if env is None: 69 env = os.environ 70 71 logname = logname or 'unknown' 72 log_dir = rospkg.get_log_dir(env=env) 73 74 # if filename is not explicitly provided, generate one using logname 75 if not filename: 76 log_filename = os.path.join(log_dir, '%s-%s.log'%(logname, os.getpid())) 77 else: 78 log_filename = os.path.join(log_dir, filename) 79 80 logfile_dir = os.path.dirname(log_filename) 81 if not os.path.exists(logfile_dir): 82 try: 83 makedirs_with_parent_perms(logfile_dir) 84 except OSError: 85 # cannot print to screen because command-line tools with output use this 86 sys.stderr.write("WARNING: cannot create log directory [%s]. Please set %s to a writable location.\n"%(logfile_dir, ROS_LOG_DIR)) 87 return None 88 elif os.path.isfile(logfile_dir): 89 raise LoggingException("Cannot save log files: file [%s] is in the way"%logfile_dir) 90 91 # the log dir itself should not be symlinked as latest 92 if logfile_dir != log_dir: 93 if sys.platform not in ['win32']: 94 try: 95 success = renew_latest_logdir(logfile_dir) 96 if not success: 97 sys.stderr.write("INFO: cannot create a symlink to latest log directory\n") 98 except OSError as e: 99 sys.stderr.write("INFO: cannot create a symlink to latest log directory: %s\n" % e) 100 101 if 'ROS_PYTHON_LOG_CONFIG_FILE' in os.environ: 102 config_file = os.environ['ROS_PYTHON_LOG_CONFIG_FILE'] 103 else: 104 # search for logging config file in /etc/. If it's not there, 105 # look for it package-relative. 106 fname = 'python_logging.conf' 107 rosgraph_d = rospkg.RosPack().get_path('rosgraph') 108 for f in [os.path.join(rospkg.get_ros_home(), 'config', fname), 109 '/etc/ros/%s'%(fname), 110 os.path.join(rosgraph_d, 'conf', fname)]: 111 if os.path.isfile(f): 112 config_file = f 113 break 114 else: 115 config_file = None 116 117 if config_file is None or not os.path.isfile(config_file): 118 # logging is considered soft-fail 119 sys.stderr.write("WARNING: cannot load logging configuration file, logging is disabled\n") 120 logging.getLogger(logname).setLevel(logging.CRITICAL) 121 return log_filename 122 123 # pass in log_filename as argument to pylogging.conf 124 os.environ['ROS_LOG_FILENAME'] = log_filename 125 # #3625: disabling_existing_loggers=False 126 logging.config.fileConfig(config_file, disable_existing_loggers=False) 127 return log_filename128130 """ 131 Create the directory using the permissions of the nearest 132 (existing) parent directory. This is useful for logging, where a 133 root process sometimes has to log in the user's space. 134 :param p: directory to create, ``str`` 135 """ 136 p = os.path.abspath(p) 137 parent = os.path.dirname(p) 138 # recurse upwards, checking to make sure we haven't reached the 139 # top 140 if not os.path.exists(p) and p and parent != p: 141 makedirs_with_parent_perms(parent) 142 s = os.stat(parent) 143 os.mkdir(p) 144 145 # if perms of new dir don't match, set anew 146 s2 = os.stat(p) 147 if s.st_uid != s2.st_uid or s.st_gid != s2.st_gid: 148 os.chown(p, s.st_uid, s.st_gid) 149 if s.st_mode != s2.st_mode: 150 os.chmod(p, s.st_mode)151 152 _logging_to_rospy_names = { 153 'DEBUG': ('DEBUG', '\033[32m'), 154 'INFO': ('INFO', None), 155 'WARNING': ('WARN', '\033[33m'), 156 'ERROR': ('ERROR', '\033[31m'), 157 'CRITICAL': ('FATAL', '\033[31m') 158 } 159 _color_reset = '\033[0m' 160211163 super(RosStreamHandler, self).__init__() 164 self._colorize = colorize 165 try: 166 from rospy.rostime import get_time, is_wallclock 167 self._get_time = get_time 168 self._is_wallclock = is_wallclock 169 except ImportError: 170 self._get_time = None 171 self._is_wallclock = None172174 level, color = _logging_to_rospy_names[record.levelname] 175 if 'ROSCONSOLE_FORMAT' in os.environ.keys(): 176 msg = os.environ['ROSCONSOLE_FORMAT'] 177 msg = msg.replace('${severity}', level) 178 msg = msg.replace('${message}', str(record.getMessage())) 179 msg = msg.replace('${walltime}', '%f' % time.time()) 180 msg = msg.replace('${thread}', str(record.thread)) 181 msg = msg.replace('${logger}', str(record.name)) 182 msg = msg.replace('${file}', str(record.pathname)) 183 msg = msg.replace('${line}', str(record.lineno)) 184 msg = msg.replace('${function}', str(record.funcName)) 185 try: 186 from rospy import get_name 187 node_name = get_name() 188 except ImportError: 189 node_name = '<unknown_node_name>' 190 msg = msg.replace('${node}', node_name) 191 if self._get_time is not None and not self._is_wallclock(): 192 t = self._get_time() 193 else: 194 t = time.time() 195 msg = msg.replace('${time}', '%f' % t) 196 msg += '\n' 197 else: 198 msg = '[%s] [WallTime: %f]' % (level, time.time()) 199 if self._get_time is not None and not self._is_wallclock(): 200 msg += ' [%f]' % self._get_time() 201 msg += ' %s\n' % record.getMessage() 202 if record.levelno < logging.WARNING: 203 self._write(sys.stdout, msg, color) 204 else: 205 self._write(sys.stderr, msg, color)206208 if self._colorize and color and hasattr(fd, 'isatty') and fd.isatty(): 209 msg = color + msg + _color_reset 210 fd.write(msg)
Home | Trees | Indices | Help |
---|
Generated by Epydoc 3.0.1 on Tue Mar 7 03:44:33 2017 | http://epydoc.sourceforge.net |