fast-reid/utils/logger.py

52 lines
1.0 KiB
Python
Raw Normal View History

2019-01-10 18:39:31 +08:00
# encoding: utf-8
"""
@author: sherlock
@contact: sherlockliao01@gmail.com
"""
2019-04-21 13:38:55 +08:00
import errno
2019-01-10 18:39:31 +08:00
import os
import sys
2019-04-21 13:38:55 +08:00
def mkdir_if_missing(dir_path):
try:
os.makedirs(dir_path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
class Logger(object):
def __init__(self, fpath=None):
self.console = sys.stdout
self.file = None
if fpath is not None:
mkdir_if_missing(os.path.dirname(fpath))
self.file = open(fpath, 'w')
def __del__(self):
self.close()
def __enter__(self):
pass
def __exit__(self, *args):
self.close()
def write(self, msg):
self.console.write(msg)
if self.file is not None:
self.file.write(msg)
def flush(self):
self.console.flush()
if self.file is not None:
self.file.flush()
os.fsync(self.file.fileno())
def close(self):
self.console.close()
if self.file is not None:
self.file.close()