python日志库loguru

 
import contextlib
from loguru import logger


APPDATA = os.getenv('APPDATA')
log_filepath = APPDATA + '\your_app\Logs\mylog.log'
logger.remove()
logger.add(log_filepath, format="{time:YYYY-MM-DD HH:mm:ss.SSS} [{level}] {message}")
logger.add(sys.__stdout__, colorize=True, format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> [{level}] {message}")
#logger.debug("block1")
#logger.info("block2")
#logger.warning("block3")
 
后面还可以加上:
 
class StreamToLogger:

    def __init__(self, level="INFO"):
        self._level = level

    def write(self, buffer):
        for line in buffer.rstrip().splitlines():
            logger.opt(depth=1).log(self._level, line.rstrip())

    def flush(self):
        pass

stream = StreamToLogger()
with contextlib.redirect_stdout(stream):
    addons = [FamikitProxy()]
redirect_stdout可能不是个好习惯,建议直接用logger.info("xxx")


原文地址:https://www.cnblogs.com/wjx0912/p/14693998.html