logger.py 4.8 KB
Newer Older
H
Hongsheng Zeng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
import errno
H
Hongsheng Zeng 已提交
16 17 18 19
import logging
import os
import os.path
import sys
20
from termcolor import colored
H
Hongsheng Zeng 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

__all__ = ['set_dir', 'get_dir', 'set_level']

# globals: logger file and directory:
LOG_DIR = None
_FILE_HANDLER = None


def _makedirs(dirname):
    assert dirname is not None
    if dirname == '' or os.path.isdir(dirname):
        return
    try:
        os.makedirs(dirname)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise e


class _Formatter(logging.Formatter):
    def format(self, record):
        msg = '%(message)s'
        if record.levelno == logging.WARNING:
            date = colored(
                '[%(asctime)s %(threadName)s @%(filename)s:%(lineno)d]',
                'yellow')
            fmt = date + ' ' + colored(
                'WRN', 'yellow', attrs=['blink']) + ' ' + msg
        elif record.levelno == logging.ERROR or record.levelno == logging.CRITICAL:
            date = colored(
                '[%(asctime)s %(threadName)s @%(filename)s:%(lineno)d]', 'red')
            fmt = date + ' ' + colored(
                'WRN', 'yellow', attrs=['blink']) + ' ' + msg
            fmt = date + ' ' + colored(
                'ERR', 'red', attrs=['blink', 'underline']) + ' ' + msg
        elif record.levelno == logging.DEBUG:
            date = colored(
                '[%(asctime)s %(threadName)s @%(filename)s:%(lineno)d]',
                'blue')
            fmt = date + ' ' + colored(
                'DEBUG', 'blue', attrs=['blink']) + ' ' + msg
        else:
            date = colored(
                '[%(asctime)s %(threadName)s @%(filename)s:%(lineno)d]',
                'green')
            fmt = date + ' ' + msg
        if hasattr(self, '_style'):
            # Python3 compatibility
            self._style._fmt = fmt
        self._fmt = fmt
        return super(_Formatter, self).format(record)


def _getlogger():
    logger = logging.getLogger('PARL')
    logger.propagate = False
    logger.setLevel(logging.DEBUG)
F
fuyw 已提交
78 79 80 81
    if 'XPARL' not in os.environ:
        handler = logging.StreamHandler(sys.stdout)
        handler.setFormatter(_Formatter(datefmt='%m-%d %H:%M:%S'))
        logger.addHandler(handler)
H
Hongsheng Zeng 已提交
82 83 84
    return logger


F
fuyw 已提交
85 86 87
def create_file_after_first_call(func_name):
    def call(*args, **kwargs):
        global _logger
B
Bo Zhou 已提交
88
        if LOG_DIR is None and hasattr(mod, '__file__'):
F
fuyw 已提交
89
            basename = os.path.basename(mod.__file__)
B
Bo Zhou 已提交
90 91
            auto_dirname = os.path.join('log_dir',
                                        basename[:basename.rfind('.')])
F
fuyw 已提交
92 93 94 95 96 97 98 99
            set_dir(auto_dirname)

        func = getattr(_logger, func_name)
        func(*args, **kwargs)

    return call


H
Hongsheng Zeng 已提交
100 101 102 103 104 105 106 107
_logger = _getlogger()
_LOGGING_METHOD = [
    'info', 'warning', 'error', 'critical', 'warn', 'exception', 'debug',
    'setLevel'
]

# export logger functions
for func in _LOGGING_METHOD:
F
fuyw 已提交
108
    locals()[func] = create_file_after_first_call(func)
H
Hongsheng Zeng 已提交
109
    __all__.append(func)
F
fuyw 已提交
110

H
Hongsheng Zeng 已提交
111 112 113 114 115 116 117 118
# export Level information
_LOGGING_LEVEL = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
for level in _LOGGING_LEVEL:
    locals()[level] = getattr(logging, level)
    __all__.append(level)


def _set_file(path):
F
fuyw 已提交
119
    global _FILE_HANDLER, _logger
H
Hongsheng Zeng 已提交
120
    if os.path.isfile(path):
121 122 123 124
        try:
            os.remove(path)
        except OSError:
            pass
H
Hongsheng Zeng 已提交
125 126 127 128 129 130 131 132
    hdl = logging.FileHandler(filename=path, encoding='utf-8', mode='w')
    hdl.setFormatter(_Formatter(datefmt='%m-%d %H:%M:%S'))

    _FILE_HANDLER = hdl
    _logger.addHandler(hdl)


def set_level(level):
F
fuyw 已提交
133
    global _logger, LOG_DIR
H
Hongsheng Zeng 已提交
134
    # To set level, need create new handler
F
fuyw 已提交
135 136
    if LOG_DIR is not None:
        set_dir(get_dir())
H
Hongsheng Zeng 已提交
137 138 139 140
    _logger.setLevel(level)


def set_dir(dirname):
F
fuyw 已提交
141
    global LOG_DIR, _FILE_HANDLER, _logger
H
Hongsheng Zeng 已提交
142 143 144
    if _FILE_HANDLER:
        # unload and close the old file handler, so that we may safely delete the logger directory
        _logger.removeHandler(_FILE_HANDLER)
F
fuyw 已提交
145
        _FILE_HANDLER.close()
H
Hongsheng Zeng 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158
        del _FILE_HANDLER

    if not os.path.isdir(dirname):
        _makedirs(dirname)
    LOG_DIR = dirname
    _set_file(os.path.join(dirname, 'log.log'))


def get_dir():
    return LOG_DIR


# Will save log to log_dir/main_file_name/log.log by default
F
fuyw 已提交
159

H
Hongsheng Zeng 已提交
160
mod = sys.modules['__main__']
B
Bo Zhou 已提交
161 162
if hasattr(mod, '__file__') and 'XPARL' not in os.environ:
    _logger.info("Argv: " + ' '.join(sys.argv))