Skip to content

Commit 973fb48

Browse files
committed
Changes to logger
1 parent 94c2e11 commit 973fb48

1 file changed

Lines changed: 30 additions & 27 deletions

File tree

  • {{cookiecutter.repo_name}}/python/{{cookiecutter.package_name}}/misc

{{cookiecutter.repo_name}}/python/{{cookiecutter.package_name}}/misc/logger.py

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88

99
# Adapted from astropy's logging system.
1010

11-
1211
from __future__ import division
1312
from __future__ import print_function
1413
from __future__ import absolute_import
@@ -23,6 +22,7 @@
2322
import sys
2423
import warnings
2524

25+
from logging import PercentStyle
2626
from logging.handlers import TimedRotatingFileHandler
2727
# from textwrap import TextWrapper
2828

@@ -32,7 +32,6 @@
3232

3333
from .color_print import color_text
3434

35-
3635
# Adds custom log level for print and twisted messages
3736
PRINT = 15
3837
logging.addLevelName(PRINT, 'PRINT')
@@ -57,11 +56,13 @@ def print_exception_formatted(type, value, tb):
5756
def colored_formatter(record):
5857
"""Prints log messages with colours."""
5958

60-
colours = {'info': ('blue', 'normal'),
61-
'debug': ('magenta', 'normal'),
62-
'warning': ('yellow', 'normal'),
63-
'print': ('green', 'normal'),
64-
'error': ('red', 'bold')}
59+
colours = {
60+
'info': ('blue', 'normal'),
61+
'debug': ('magenta', 'normal'),
62+
'warning': ('yellow', 'normal'),
63+
'print': ('green', 'normal'),
64+
'error': ('red', 'bold')
65+
}
6566

6667
levelname = record.levelname.lower()
6768

@@ -70,19 +71,23 @@ def colored_formatter(record):
7071

7172
if levelname.lower() in colours:
7273
levelname_color = colours[levelname][0]
73-
header = color_text('[{}]: '.format(levelname.upper()), levelname_color)
74+
header = color_text('[{}]: '.format(levelname.upper()),
75+
levelname_color)
7476

7577
message = '{0}'.format(record.msg)
7678

7779
warning_category = re.match('^(\w+Warning\:).*', message)
7880
if warning_category is not None:
79-
warning_category_colour = color_text(warning_category.groups()[0], 'cyan')
80-
message = message.replace(warning_category.groups()[0], warning_category_colour)
81+
warning_category_colour = color_text(warning_category.groups()[0],
82+
'cyan')
83+
message = message.replace(warning_category.groups()[0],
84+
warning_category_colour)
8185

8286
sub_level = re.match('(\[.+\]:)(.*)', message)
8387
if sub_level is not None:
8488
sub_level_name = color_text(sub_level.groups()[0], 'red')
85-
message = '{}{}'.format(sub_level_name, ''.join(sub_level.groups()[1:]))
89+
message = '{}{}'.format(sub_level_name, ''.join(
90+
sub_level.groups()[1:]))
8691

8792
# if len(message) > 79:
8893
# tw = TextWrapper()
@@ -105,39 +110,36 @@ class MyFormatter(logging.Formatter):
105110

106111
ansi_escape = re.compile(r'\x1b[^m]*m')
107112

108-
def __init__(self, fmt='%(levelname)s - %(message)s [%(funcName)s @ ' +
109-
'%(filename)s]'):
110-
logging.Formatter.__init__(self, fmt, datefmt='%Y-%m-%d %H:%M:%S')
111-
112113
def format(self, record):
113114

114115
# Save the original format configured by the user
115116
# when the logger formatter was instantiated
116-
format_orig = self._fmt
117+
# format_orig = self._fmt
117118

118119
# Replace the original format with one customized by logging level
120+
119121
if record.levelno == logging.DEBUG:
120-
self._fmt = MyFormatter.info_fmt
122+
self._style = PercentStyle(MyFormatter.info_fmt)
121123

122124
elif record.levelno == logging.getLevelName('PRINT'):
123-
self._fmt = MyFormatter.info_fmt
125+
self._style = PercentStyle(MyFormatter.info_fmt)
124126

125127
elif record.levelno == logging.INFO:
126-
self._fmt = MyFormatter.info_fmt
128+
self._style = PercentStyle(MyFormatter.info_fmt)
127129

128130
elif record.levelno == logging.ERROR:
129-
self._fmt = MyFormatter.info_fmt
131+
self._style = PercentStyle(MyFormatter.info_fmt)
130132

131133
elif record.levelno == logging.WARNING:
132-
self._fmt = MyFormatter.warning_fmp
134+
self._style = PercentStyle(MyFormatter.warning_fmt)
133135

134-
record.msg = self.ansi_escape.sub('', record.msg)
136+
# record.msg = self.ansi_escape.sub('', record.msg)
135137

136138
# Call the original formatter class to do the grunt work
137139
result = logging.Formatter.format(self, record)
138140

139141
# Restore the original format configured by the user
140-
self._fmt = format_orig
142+
# self._fmt = format_orig
141143

142144
return result
143145

@@ -248,12 +250,13 @@ def start_file_logger(self, path, log_file_level=logging.DEBUG):
248250
if not os.path.exists(logdir):
249251
os.mkdir(logdir)
250252

251-
# If the log file exists, backs it up before creating a new file handler
252253
if os.path.exists(log_file_path):
253-
strtime = datetime.datetime.utcnow().strftime('%Y-%m-%d_%H:%M:%S')
254+
strtime = datetime.datetime.utcnow().strftime(
255+
'%Y-%m-%d_%H:%M:%S')
254256
shutil.move(log_file_path, log_file_path + '.' + strtime)
255257

256-
self.fh = TimedRotatingFileHandler(str(log_file_path), when='midnight', utc=True)
258+
self.fh = TimedRotatingFileHandler(
259+
str(log_file_path), when='midnight', utc=True)
257260
self.fh.suffix = '%Y-%m-%d_%H:%M:%S'
258261
except (IOError, OSError) as ee:
259262
warnings.warn('log file {0!r} could not be opened for writing: '
@@ -263,7 +266,7 @@ def start_file_logger(self, path, log_file_level=logging.DEBUG):
263266
self.addHandler(self.fh)
264267
self.fh.setLevel(log_file_level)
265268

266-
self.log_filename = log_file_path
269+
self.log_filename = log_file_path
267270

268271

269272
logging.setLoggerClass(MyLogger)

0 commit comments

Comments
 (0)