Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FEA:logger #5

Merged
merged 2 commits into from
Jun 29, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions utils/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import logging
import os


class Logger(object):

def __init__(self, logfilename):
"""
A logger that can show a message on standard output and write it into the
file named `filename` simultaneously.
All the message that you want to log MUST be str.

:param logfilename: file name that log saved
example:
logger = Logger('train.log')
logger.debug(train_state)
logger.info(train_result)

"""

self.LOGROOT='./log'
dir_name = os.path.dirname(self.LOGROOT)
if not os.path.exists(dir_name):
os.makedirs(dir_name)

self.logger = logging.getLogger(logfilename)
self.logger.setLevel(logging.DEBUG)

logfilepath = os.path.join(self.LOGROOT, logfilename)

fmt = "%(asctime)-15s %(levelname)s %(filename)s %(lineno)d %(process)d %(message)s"
datefmt = "%a %d %b %Y %H:%M:%S"
formatter = logging.Formatter(fmt, datefmt)

fh = logging.FileHandler(logfilepath)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
self.logger.addHandler(fh)

sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
sh.setFormatter(formatter)
self.logger.addHandler(sh)

def debug(self, message):
self.logger.debug(message)

def info(self, message):
self.logger.info(message)

def warning(self, message):
self.logger.warning(message)

def error(self, message):
self.logger.error(message)

def critical(self, message):
self.logger.critical(message)


if __name__ == '__main__':
log = Logger('NeuRec.log')
log.debug('debug')
log.info('info')
log.warning('warning')
log.error('error')
log.critical('critical')