Set logging timestamp
[ros_wild_thumper.git] / src / wild_thumper / ros_logging.py
1 #!/usr/bin/env python
2 # -*- coding: iso-8859-15 -*-
3 #
4 # see https://answers.ros.org/question/174892/ros-log-file-change-of-time-stamping-format/
5
6 import os
7 import time
8 import logging
9 import sys
10 import datetime
11 from rosgraph.roslogging import RosStreamHandler as _RosStreamHandler, _logging_to_rospy_names, _defaultFormatter
12
13
14 class RosStreamHandler(_RosStreamHandler):
15         def emit(self, record):
16                 level, color = _logging_to_rospy_names[record.levelname]
17                 record_message = _defaultFormatter.format(record)
18                 msg = os.environ.get('ROSCONSOLE_FORMAT', '[${severity}] [${time}]: ${message}')
19                 msg = msg.replace('${severity}', level)
20                 msg = msg.replace('${message}', str(record_message))
21                 msg = msg.replace('${walltime}', '%f' % time.time())
22                 msg = msg.replace('${thread}', str(record.thread))
23                 msg = msg.replace('${logger}', str(record.name))
24                 msg = msg.replace('${file}', str(record.pathname))
25                 msg = msg.replace('${line}', str(record.lineno))
26                 msg = msg.replace('${function}', str(record.funcName))
27                 try:
28                         from rospy import get_name
29                         node_name = get_name()
30                 except ImportError:
31                         node_name = '<unknown_node_name>'
32                 msg = msg.replace('${node}', node_name)
33                 time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
34                 msg = msg.replace('${time}', time_str)
35                 msg += '\n'
36                 if record.levelno < logging.WARNING:
37                         self._write(sys.stdout, msg, color)
38                 else:
39                         self._write(sys.stderr, msg, color)